<?php

/*
* NOTES TO SELF:
*
* 1. when you use $this->view->render($path), $path has to *either* be an absolute
*    path *or* a relative path starting in /application/views/scripts.l
*
* 2. for lots and lots of runtime errors in ZF you get a bogus "Invalid controller
*    specified" message.
*review
* 3. DO NOT put underscores in you
* r controller or action names unless you're putting
*    in a corresponding directory tree.
*/

function fdLicenseCompare( &$r1, &$r2 )
{
	if($r1['license_number'] < $r2['license_number']) return -1;
	if($r1['license_number'] > $r2['license_number']) return 1;
	return 0;
}

class IndexController extends Zend_Controller_Action
{
	private $_user_id = -1;
	private $_username = "";
	private $_pers_info = null;
	private $_fd_id = -1;
	private $_ks_id = -1;
	private $_fh_id = -1;
	private $_fh_admin = false;
	private $_role_name = "";
	private $_permissions = null;
	private $_nav_urls = null;

	protected $_flashMessenger = null;

	public function init()
	{
		$ajaxHelper = $this->_helper->getHelper("AjaxContext");

		// set Dojo-grid-related methods to type 'json'
		$ajaxHelper->addActionContext( 'importfuneralhomes', 'json' );
		$ajaxHelper->addActionContext( 'importfuneraldirectorsandcases', 'json' );

		$ajaxHelper->addActionContext( 'kscases', 'json' );
		$ajaxHelper->addActionContext( 'kscashadvances', 'json' );
		$ajaxHelper->addActionContext( 'ksfuneraldirectors', 'json' );
		$ajaxHelper->addActionContext( 'ksfuneralhomes', 'json' );
		$ajaxHelper->addActionContext( 'ksmerchandise', 'json' );

		$ajaxHelper->addActionContext( 'fdpreregcases', 'json' );
		$ajaxHelper->addActionContext( 'fdpendingcases', 'json' );
		$ajaxHelper->addActionContext( 'fdfinishedcases', 'json' );

		$ajaxHelper->addActionContext( 'vasmerchandiseforbranch', 'json' );
		$ajaxHelper->addActionContext( 'vascashadvancesforlocale', 'json' );
		$ajaxHelper->addActionContext( 'vasservicesforlocale', 'json' );
		$ajaxHelper->addActionContext( 'vaspackagesforlocale', 'json' );

		$ajaxHelper->addActionContext( 'caterersandmenus', 'json' );
		$ajaxHelper->addActionContext( 'updatecaterersandmenus', 'json' );
		$ajaxHelper->addActionContext( 'floristsandcollections', 'json' );
		$ajaxHelper->addActionContext( 'updatefloristsandcollections', 'json' );

		$ajaxHelper->addActionContext( 'addvastimingrecord', 'json' );

		$ajaxHelper->initContext();

		$this->_flashMessenger = $this->getHelper('FlashMessenger');
		$this->_flashMessenger->setNameSpace("VAS");
	}

	protected function isLoggedIn()
	{
		$ns = new Zend_Session_Namespace("VAS");
		return isset($ns->user_profile);
	}

	protected function isFuneralDirector()
	{
		$ns = new Zend_Session_Namespace("VAS");
		return $ns->user_profile['role_name'] == "FD";
	}

	protected function isFuneralHomeAdmin()
	{
		$ns = new Zend_Session_Namespace("VAS");
		return $ns->user_profile['role_name'] == "FD_Admin";
	}

	protected function isKeystoneAdmin()
	{
		$ns = new Zend_Session_Namespace("VAS");
		return $ns->user_profile['role_name'] == "Admin";
	}

	public function indexAction()
	{
		$this->view->title = "Main Page";

		if($this->isLoggedIn())
		{
			if($this->isFuneralDirector())
			{
				$this->_redirect('/index/fddashboard');
				return;
			}
			else
			if($this->isKeystoneAdmin())
			{
				$this->_redirect('/index/admindashboard');
				return;
			}
		}

		$this->_redirect('/index/login');
	}

	public function loginAction()
	{
		$ns = new Zend_Session_Namespace("VAS");

		$this->_helper->layout->setLayout('VAS_login');

		$r = $this->getRequest();
		if($r->isPost())
		{
			$username = $r->getParam('username');
			$password = $r->getParam('password');
			if(empty($username) || empty($password))
			{
				$this->_redirect('/index/login');
			}

			$users = new Users();
			$results = $users->checkUsernameAndPassword( $username, $password );
			if($results['status'] == "SUCCEEDED")
			{
				// set the user profile into the session cache
				$user_profile = $results['rows'][0];

				$ns->user_profile = $user_profile;
				if($user_profile['role_name'] == "Admin")
				{
					// if it's an administrator, redirect to /index/admindashboard
					$ns->fh_id = -1; // not attached to any funeral home?
					$ns->fd_id = -1; // not a funeral director?
					$ns->fd_license_num = ''; // no FD license num
					$ns->ks_id = $user_profile['id'];

					//ADDME - add invocation to get new funeral homes into db so the grid fetch methods can
					// bring them in.

					$this->_redirect('/index/admindashboard');
				}
				else
				if($user_profile['role_name'] == "FD" || $user_profile['role_name'] == "FD_Admin")
				{
					// if it's a funeral director, redirect to /index/fddashboard
					$ns->fh_id = $user_profile['FDMS_funeral_home_id'];
					$ns->fd_id = $user_profile['FDMS_funeral_director_id'];
					$ns->fd_license_num = $user_profile['FDMS_license_number'];

					$fhModel = new FuneralHomes();
					$this->_redirect('/index/fddashboard');
				}

			}
			else
			if($results['status'] == "FAILED_BAD_CREDENTIALS")
			{
				// add  flash message TEO "Invalid username or password"
				$this->_flashMessenger->addMessage("Invalid username or password");
			}
			else
			{
				// add flash message TEO "Server error - contact support"
				$this->_flashMessenger->addMessage("Database error - contact User Support");
			}
		}

		// add flash messages to $this->view and let the login.phtml script
		// sort it out.
		$this->view->messages = $this->_flashMessenger->getMessages();
	}

	public function logoutAction()
	{
		$ns = new Zend_Session_Namespace("VAS");

		$this->_username = "";
		$this->_user_id = -1;
		$this->_role_name = "";
		$this->_permissions = null;
		$this->_pers_info = null;
		$this->_ks_id = -1;
		$this->_fd_id = -1;
		$this->_fh_id = -1;
		$this->_fh_admin = false;

		Zend_Session::destroy();

		$this->_redirect('/index/login');
	}

	///////////////////////////////////////////////////////////////////////////////
	// KEYSTONE ADMIN METHODS

	public function admindashboardAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		//		$this->importfuneralhomes();

		$this->view->user_profile = $ns->user_profile;
		$this->view->is_dashboard = true;
		$this->view->pageName = "DASHBOARD";
	}

	// quick hack - go thru users and fetch each FD record
	// then unpack branches and get branch number for each branch id.

	public function getbranchnumbersAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$users = new Users();
		$homes = new FuneralHomes();

		$fds = $users->fetchAll("role_name = 'FD'");
		foreach( $fds as $fd )
		{
			$license = $fd->FDMS_license_number;
			$branches_str = $fd->branches;
			$branch_ids = explode( ",", $branches_str );
			$branch_nums = array();
			foreach( $branch_ids as $branch_id )
			{
				$r = $homes->fetchRow( "branch_id = '$branch_id'" );
				if($r)
				{
					$branch_nums[] = $r->branch_number;
				}
			}
			$branchnums = implode(",", $branch_nums);
			$p = array( 'branchnums'=>$branchnums );
			$users->update( $p, "FDMS_license_number='$license'" );
			echo "$license:$branches_str:$branchnums<br>";
		}
	}

	public function administratorsAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$this->view->user_profile = $ns->user_profile;

		$users = new Users();
		$results = $users->fetchAdminUsers();
		$this->view->admins = $results['rows'];
	}

	public function newadministratorAction()
	{
		$this->_flashMessenger = $this->getHelper('FlashMessenger');
		$this->_flashMessenger->setNameSpace("VAS");

		$messages = $this->_flashMessenger->getMessages();

		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$users = new Users();

		$this->view->user_profile = $ns->user_profile;

		$this->view->adminProfile = null;

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getParams();

			$adminProfile = array();

			$adminProfile["fname"] = $p["fname"];
			$adminProfile["mname"] = $p["mname"];
			$adminProfile["lname"] = $p["lname"];
			$adminProfile["address"] = $p["address"];
			$adminProfile["city"] = $p["city"];
			$adminProfile["state"] = $p["state"];
			$adminProfile["zip"] = $p["zip"];
			$adminProfile["phone"] = $p["phone"];
			$adminProfile["email"] = $p["email"];

			$adminProfile["username"] = $p['username'];
			$adminProfile["password"] = $p['password'];

			$adminForm = new AdministratorForm();
			if($adminForm->isValid($adminProfile))
			{
				$users->createAdministratorUser( $adminProfile );
				$this->_redirect("/index/administrators");
			}

			$this->view->adminProfile = $adminProfile;
		}

		$this->view->messages = $this->_flashMessenger->getMessages();
	}

	public function editadministratorAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$req = $this->getRequest();
		$VAS_admin_id = $req->getParam('id');
		$this->view->adminToEditID = $VAS_admin_id;

		$users = new Users();
		$results = $users->getUser( $VAS_admin_id );

		$this->view->adminProfile = $results['rows'][0];
		$this->view->user_profile = $ns->user_profile;

		if($req->isPost())
		{
			$p = $req->getParams();

			$adminProfile = array();

			$adminProfile["fname"] = $p["fname"];
			$adminProfile["mname"] = $p["mname"];
			$adminProfile["lname"] = $p["lname"];
			$adminProfile["address"] = $p["address"];
			$adminProfile["city"] = $p["city"];
			$adminProfile["state"] = $p["state"];
			$adminProfile["zip"] = $p["zip"];
			$adminProfile["phone"] = $p["phone"];
			$adminProfile["email"] = $p["email"];
			$adminProfile["username"] = $p["username"];
			$adminProfile["password"] = $p["password"];

			$username = $p['username'];
			$password = $p['password'];

			$adminForm = new AdministratorForm();
			if($adminForm->isValid( $adminProfile ))
			{
				$results = $users->updateAdministratorUser( $adminProfile, $VAS_admin_id );
				$this->_redirect('/index/administrators');
			}
			else
			$this->view->adminProfile = $adminProfile;
		}

		$this->view->messages = $this->_flashMessenger->getMessages();
		$this->view->adminProfile = $results['rows']['0'];
	}

	public function adminhelpAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$this->view->user_profile = $ns->user_profile;
	}

	public function adminprofileAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$VAS_user_id = $ns->user_profile['id'];

		$users = new Users();

		$this->view->user_profile = $ns->user_profile;

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getParams();

			$profile = array();
			$profile['fname'] = $p['fname'];
			$profile['mname'] = $p['mname'];
			$profile['lname'] = $p['lname'];
			$profile['address'] = $p['address'];
			$profile['city'] = $p['city'];
			$profile['state'] = $p['state'];
			$profile['zip'] = $p['zip'];
			$profile['phone'] = $p['phone'];
			$profile['email'] = $p['email'];

			$adminForm = new AdministratorForm();
			if($adminForm->isValid($profile))
			{
				$results = $users->updateAdministratorUser( $profile, $VAS_user_id );
				if($results['status'] == "SUCCEEDED")
				{
					$profile['id'] = $VAS_user_id;
					$ns->user_profile = $profile;
				}

				$this->_redirect('/index/admindashboard');
			}
			else
			$this->view->user_profile = $profile;
		}
		else
		{
		}
	}


	public function funeralhomeAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$ks_id = $ns->ks_id;
		$funeralHomes = new FuneralHomes();
		// GET request, which means displaying the funeral home profile
		// in a form

		$branch_number = $req->getParam("branch_number");

		$results = $funeralHomes->getHomeByFDMSId($branch_number);
		if($results['status'] != "SUCCEEDED")
		{
			$this->_redirect('/index/admindashboard');
		}

		$this->view->branch_number = $branch_number;

		$moduleTimesModel = new VASModuleTimes();
		$stats2 = $moduleTimesModel->moduleStatsForBranch($branch_number);
		if(null == $stats2) $stats2 = array();
		$this->view->quickStats = $stats2;

		$funeral_home = $results['rows'][0];

		$ks_admins = new Administrators();
		$this->view->user_profile = $ns->user_profile;

		if($req->isPost())
		{
			$p = $req->getParams();

			$branch_number = $p['branch_number'];

			// sift the fhProfile fields out of the request data
			$fhProfile = array();

			$fhProfile['manager_name'] = $p['manager_name'];
			$fhProfile['region'] = $p['region'];
			$fhProfile['primary_email'] = $p['primary_email'];
			$fhProfile['name'] = $p['name'];
			$fhProfile['addr1'] = $p['addr1'];
			$fhProfile['city'] = $p['city'];
			$fhProfile['state'] = $p['state'];
			$fhProfile['zip'] = $p['zip'];
			$fhProfile['phone'] = $p['phone'];
			$fhProfile['modules'] = $p['modules'];
			$fhProfile['url'] = $p['url'];
			$fhProfile['show_packages'] = $p['show_packages'];

			$photo_upload = new Zend_File_Transfer_Adapter_Http();
			$photo_upload->setDestination(ROOT_DIR.'/upload');
			$photo_received = $photo_upload->receive("photo_image");
			if($photo_received)
			{
				$photo_info = $photo_upload->getFileInfo("photo_image");
				$srcPath = $photo_info['photo_image']['name'];
				if(!empty($srcPath))
				{
					// split the uploaded (temp) filename into parts so we can rename it
					$parts = pathinfo($srcPath, PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME);
					$srcExt = $parts['extension'];
					$srcFilename = $parts['basename'];
					$dstFilename = "FH_{$branch_number}_profile_pic.{$srcExt}";

					$srcPath = $_SERVER['DOCUMENT_ROOT'].'/Zend-Project/upload/'.$srcFilename;
					$dstPath =  ARTWORK_DIR."/FH/$dstFilename";

					echo "$srcPath to $dstPath<br>";
					if(copy( $srcPath, $dstPath))
					{
						$results = $funeralHomes->setPictureImageForFuneralHomeBranchNumber( $dstFilename, $branch_number );
						Zend_Debug::dump($results);
						$fhProfile['photo_image'] = $dstFilename;
					}
					else
					{
					}
				}
			}

			$logo_upload = new Zend_File_Transfer_Adapter_Http();
			$logo_upload->setDestination(ROOT_DIR.'/upload');
			$logo_received = $logo_upload->receive("logo_image");
			if($logo_received)
			{
				$logo_info = $logo_upload->getFileInfo("logo_image");
				$srcPath = $logo_info['logo_image']['name'];
				if(!empty($srcPath))
				{
					// split the uploaded (temp) filename into parts so we can rename it
					$parts = pathinfo($srcPath, PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME);

					$srcExt = $parts['extension'];
					$srcFilename = $parts['basename'];
					$dstFilename = "FH_{$branch_number}_logo_pic.{$srcExt}";

					$dstPath =  ARTWORK_DIR."/FH/$dstFilename";
					$srcPath = $_SERVER['DOCUMENT_ROOT'].'/Zend-Project/upload/'.$srcFilename;
					if(copy( $srcPath, $dstPath))
					{
						$results = $funeralHomes->setLogoImageForFuneralHomeBranchNumber( $dstFilename, $branch_number );
						$fhProfile['logo_image'] = $dstFilename;
					}
					else
					{
					}
				}
			}

			$branch_number = $p['branch_number'];

			$fhForm = new FHProfileForm();
			if($fhForm->isValid( $fhProfile ))
			{
				$branch_number = $p['branch_number'];
				$results = $funeralHomes->setProfileForFDMSId( $fhProfile, $branch_number );
			}
			else
			{
				// add flash message indicating problem and maybe error indicator to $this->view
			}

			$funeral_home = $fhProfile;

			$funeral_home['branch_number'] = $branch_number;
			$this->_redirect('/index/funeralhome/branch_number/'.$branch_number);
		}

		$casesModel = new FDMSCases();

		$this->view->numOpenCases = $casesModel->countOpenCasesForBranchNumber( $branch_number );
		$this->view->funeral_home = $funeral_home;
		$this->view->branch_number = $branch_number;
		$this->view->VAS_fh_id = $VAS_fh_id;
		$this->view->is_from_admin = true;

		$region = $funeral_home['region'];
		if(empty($region)) $region = -1;

		$vasModuleTimes = new VASModuleTimes();
		$casesModel = new FDMSCases();

		// 1. branch level stats
		// 2. arranger level stats
		// 3. company wide stats

		$this->view->bstats = $vasModuleTimes->statsForBranch( $branch_number );
		$this->view->brevs = $casesModel->getCaseStatsForBranch( $branch_number );

		$this->view->rstats = $vasModuleTimes->statsForRegion( $region );
		$this->view->rrevs = $casesModel->getCaseStatsForRegion( $region );

		$this->view->cstats = $vasModuleTimes->statsForCompany();
		$this->view->crevs = $casesModel->getCaseStatsForCompany();
	}

	public function funeralhomesettingsAction()
	{
		// settings - right now it's module sequence
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$req = $this->getRequest();

		$branch_number = $req->getParam('branch_number');
		if(empty($branch_number))
		$this->_redirect('/index/admindashboard');

		$this->view->branch_number = $branch_number;
		$this->view->user_profile = $ns->user_profile;
	}

	public function funeralhomemerchandiseAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');
		$ns = new Zend_Session_Namespace("VAS");

		// show admin dashboard page
		if(!$this->isLoggedIn() || !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		if(!isset($ns->ks_id))
		$this->_redirect('/index/login');

		$topMerchModel = new LocaleTopMerchandise();

		$req = $this->getRequest();

		$branch_number = $req->getParam('branch_number');
		$this->view->branch_number = $branch_number;

		if($req->isGet() && empty($branch_number))
		$this->_redirect('/index/admindashboard');

		$funeralHomes = new FuneralHomes();

		$results = $funeralHomes->getProfileForBranchNumber( $branch_number );
		$fh = $results['rows'][0];
		$this->view->fh = $fh;

		$this->view->funeralhome_id = $fh_id;
		$this->view->VAS_fh_id = $fh_id;

		$localeId = $fh['locale_id'];
		$this->view->locale_id = $localeId;
		if($req->isPost())
		{
			// if this is a POST request,
			$cartXML = $req->getParam('cartXML');
			$featuredItems = simplexml_load_string( $cartXML );

			$localeId = $req->getParam('locale_id');

			$items = array();
			// make an array out of $cartItems
			foreach($featuredItems->featuredItem as $featuredItem)
			{
				$item = array();

				$item['price_list_id'] = $featuredItem->price_list_id;
				$item['item_name'] = "".$featuredItem->name;
				$item['item_price'] = "".$featuredItem->price;
				$item['picture'] = "".$featuredItem->picture;
				$item['locale_id'] = $localeId;

				//				$item['item_category'] = "".$featuredItem->item_category;

				$items[] = $item;
			}

			// set the cart items
			$results = $topMerchModel->setTopMerchandiseForLocale( $items, $localeId );

			$this->_redirect('/index/funeralhomemerchandise/branch_number/'.$branch_number);
		}

		$funeralHomes = new FuneralHomes();
		// hmm.  maybe get all branches for this locale id and add
		// them to the mix? not sure why.
		$this->view->locale_id = $localeId;
		$results = FDMSAPIcalls::getMerchandiseForLocaleId( $localeId );

		$rawmerch = $results['rows'];
		$merchandise = array();
		foreach( $rawmerch as $merch_item )
		{
			if($merch_item['item_category']=='SRV' ||
			$merch_item['item_category']=='ADV' ||
			$merch_item['item_category']=='DIS') continue;
			$merchandise[] = $merch_item;
		}

		$this->view->catalog = $merchandise;
		$results = $topMerchModel->getTopMerchandiseForLocale( $localeId );
		$this->view->cart = $results['rows'];

		$this->view->branch_number = $branch_number;
		$this->view->pageName = "LOCALEMERCHANDISE";
		$this->view->user_profile = $ns->user_profile;
	}


	public function funeraldirectorAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() || !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$ks_admins = new Administrators();

		$this->view->user_profile = $ns->user_profile;

		$users = new Users();

		//		$FDMS_license_number = "";

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getParams();

			$FDMS_license_number = $p['FDMS_license_number'];

			$results = $users->getFuneralDirectorForFDMSLicenseNum( $FDMS_license_number );
			$stored_fd_profile = $results['rows'][0];

			$posted_fd_profile = array();

			$posted_fd_profile['full_name'] = $p['full_name'];
			// add password
			$posted_fd_profile['username'] = $p['username'];
			$posted_fd_profile['password'] = $p['password'];
			$posted_fd_profile['fname'] = $p['fname'];
			$posted_fd_profile['mname'] = $p['mname'];
			$posted_fd_profile['lname'] = $p['lname'];
			$posted_fd_profile['address'] = $p['address'];
			$posted_fd_profile['city'] = $p['city'];
			$posted_fd_profile['state'] = $p['states'];
			$posted_fd_profile['zip'] = $p['zip'];
			$posted_fd_profile['phone'] = $p['phone'];
			$posted_fd_profile['email'] = $p['email'];

			$branch_number = $p['branch_number'];
			$FDMS_license_number = $p['FDMS_license_number'];

			$upload = new Zend_File_Transfer_Adapter_Http();
			$upload->setDestination(ROOT_DIR."/upload/");

			try
			{
				// upload received file(s)
				if($upload->receive($p['photo_image']))
				{
					// make sure we *have* a srcPath.
					$srcPath = $upload->getFileName();
					if(!empty($srcPath))
					{
						// split the uploaded (temp) filename into parts so we can rename it
						$parts = pathinfo($srcPath, PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME);

						$srcExt = $parts['extension'];
						$srcFilename = $parts['filename'];
						$dstFilename = "FD_{$fdid}_profile_pic.{$srcExt}";

						$dstPath =  ARTWORK_DIR."/FD/$dstFilename";

						if(copy( $srcPath, $dstPath))
						$posted_fd_profile['photo'] = $dstFilename;
					}
					else
					{
						$posted_fd_profile['photo'] = $stored_fd_profile['photo'];
					}
				}
			}
			catch (Zend_File_Transfer_Exception $e)
			{
				echo $e->getMessage();
				$posted_fd_profile['photo'] = $stored_fd_profile['photo'];
			}

			// now update the rest of the fields for the FD
			$users->updateFDMSFDUser( $posted_fd_profile, $FDMS_license_number );

		}
		else
		{
			$FDMS_license_number = $req->getParam("funeraldir_id");
			$branch_number = $req->getParam("branch_number");
		}

		if(!isset($FDMS_license_number)) $this->_redirect('/index/admindashboard');

		$this->view->FDMS_license_number = $FDMS_license_number;
		$moduleTimesModel = new VASModuleTimes();

		$result = $users->getFuneralDirectorForFDMSLicenseNum( $FDMS_license_number );

		if($result['status'] == "SUCCEEDED")
		{
			$funeral_dir = $result['rows'][0];

			$this->view->funeral_dir_profile = $funeral_dir;

			if(!isset($branch_number)) $branch_number = -1;
			$this->view->branch_number = $branch_number;

			// need to look up funeral home for branch number
			$homes = new FuneralHomes();
			$results = $homes->getProfileForBranchNumber( $branch_number );
			if($results['status'] == "SUCCEEDED")
			{
				$funeral_home = $results['rows'][0];
				$region = $funeral_home['region'];
			}
			else
			$region = -1;

			// now grab stats for arranger, branch, region, and company

			$vasModuleTimes = new VASModuleTimes();
			$casesModel = new FDMSCases();

			// 1. branch level stats
			// 2. arranger level stats
			// 3. region level stats
			// 4. company wide stats

			$FDids = explode(",", $funeral_dir['FD_ids']);
			$branchnums = explode(",", $funeral_dir['branchnums']);

			if(count($FDids) == count($branchnums))
			{
				// search $branchnums for $branch_number and use idx to index $FDids
				// get stats for arranger
				$idx = -1;
				$fd_id_value = -1;
				for( $i=0; $i<count($branchnums); $i++ )
				{
					if($branchnums[$i] == $branch_number)
					{
						$fd_id_value = $FDids[$i];
						$idx = $i;
						break;
					}
				}
			}
			else
			{
				// set message to "Unable to map" or some such
				$fd_id_value = -1;
			}

			$stats1 = $vasModuleTimes->moduleStatsForArranger( $fd_id_value );
			$this->view->quick_stats = $stats1;
			//echo "getting stats for arranger<br>";
			$this->view->astats = $vasModuleTimes->statsForArranger( $fd_id_value );
			$this->view->arevs = $casesModel->getCaseStatsForArranger( $fd_id_value );
			//echo "getting stats for branch<br>";
			$this->view->bstats = $vasModuleTimes->statsForBranch( $branch_number );
			$this->view->brevs = $casesModel->getCaseStatsForBranch( $branch_number );
			//echo "getting stats for region<br>";
			$this->view->rstats = $vasModuleTimes->statsForRegion( $region );
			$this->view->rrevs = $casesModel->getCaseStatsForRegion( $region );
			//echo "getting stats for company<br>";
			$this->view->cstats = $vasModuleTimes->statsForCompany();
			$this->view->crevs = $casesModel->getCaseStatsForCompany();
			//echo "finis<br>";*/
			echo $this->view->render('index/keystoneadmin_funeraldirectorprofile.phtml');
		}
		else
		{
			$this->_redirect('/index/admindashboard');
		}
	}

	public function funeraldirectormodulesAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() || !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$req = $this->getRequest();

		$FDMS_license_number = $req->getParam("funeraldir_id");
		if(empty($FDMS_license_number))
		$this->_redirect('/index/admindashboard');

		$ks_id = $ns->ks_id;

		$ks_admins = new Administrators();
		$users = new Users();

		$this->view->user_profile = $ns->user_profile;
		$this->view->FDMS_license_number = $FDMS_license_number;

		$funeralHomes = new FuneralHomes();

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getParams();
			$module_order = $req->getParam('module_order');
			$module_order_str = implode("|", $module_order);
			$results = $users->setModulesForFuneralDirector( $module_order_str, $FDMS_license_number );
		}

		$results = $users->getModulesForFuneralDirector( $FDMS_license_number );
		if($results['status'] == "SUCCEEDED")
		{
			$modules = $results['modules'];
		}
		else
		{
			$this->_redirect('/index/admindashboard');
		}

		$this->view->modules = $modules;
		$this->view->pageName = "MODULEEDITOR";
	}

	public function reviewcaseAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$this->view->user_profile = $ns->user_profile;

		$req = $this->getRequest();
		if($req->isGet())
		{
			$case_id = $req->getParam('case_id');
			if(!isset($case_id))
			$this->_redirect('/index/admindashboard');
		}
		else
		if($req->isPost())
		{

		}

		$cases = new FDMSCases();
		$result = $cases->getCaseInfoForFDMSVitalsId($case_id);
		$case = $result['rows'][0];
		$case_num = $case['FDMS_case_num'];
		$caseNumber = $case['FDMS_case_num'];

		$usersModel = new Users();
		$fhModel = new FuneralHomes();

		//ADDME - get merch,
		//ASKME - get $fdms_branch_id_str too?
		$fdms_branch_number = $case['branch_num'];
		$fdms_funeral_dir_id = $case['FDMS_funeral_director_id'];

		$rr = $fhModel->getProfileForBranchNumber($fdms_branch_number);
		$home = $rr['rows'][0];

		$rr = $usersModel->getFuneralDirectorForFDMSId( $fdms_funeral_dir_id );

		$caseServices = new CaseServices();
		$caseCashAdvances = new CaseCashAdvances();
		$caseMerchandise = new CaseMerchandise();

		$errors = array();
		$request = $this->getRequest();
		if($request->isPost())
		{
			# validate params and update case record if needed
			# note - since I'm not using ZFW's misbegotten form builder
			# I will need to do my own error message method

			$case_profile = array();
			$p = $request->getParams();

			$caseNumber = $p['FDMS_case_num'];

			$case_profile['service_date'] = $p['service_date'];
			$case_profile['service_time'] = $p['service_time'];
			$case_profile['decedent_dob'] = $p['decedent_dob'];
			$case_profile['decedent_dod'] = $p['decedent_dod'];
			$case_profile['decedent_fname'] = $p['decedent_fname'];
			$case_profile['decedent_mname'] = $p['decedent_mname'];
			$case_profile['decedent_lname'] = $p['decedent_lname'];
			$case_profile['decedent_race'] = $p['decedent_race'];
			$case_profile['decedent_sex'] = $p['decedent_sex'];
			$case_profile['decedent_birth_city'] = $p['decedent_birth_city'];
			$case_profile['decedent_birth_state'] = $p['decedent_birth_state'];
			$case_profile['decedent_birth_country'] = $p['decedent_birth_country'];
			$case_profile['decedent_death_city'] = $p['decedent_death_city'];
			$case_profile['decedent_death_state'] = $p['decedent_death_state'];
			$case_profile['decedent_death_country'] = $p['decedent_death_country'];
			$case_profile['death_location_address'] = $p['decedent_death_location_address'];
			$case_profile['death_location_name'] = $p['decedent_death_location_name'];
			$case_profile['decedent_primary_education'] = $p['decedent_primary_education'];
			$case_profile['decedent_secondary_education'] = $p['decedent_secondary_education'];
			$case_profile['decedent_occupation'] = $p['decedent_occupation'];
			$case_profile['decedent_business'] = $p['decedent_business'];
			$case_profile['decedent_company_name'] = $p['decedent_company_name'];
			$case_profile['decedent_marital_status'] = $p['decedent_marital_status'];
			$case_profile['decedent_surv_spouse'] = $p['decedent_surv_spouse'];

			if(isset($p['decedent_lived_in_city']))
			$case_profile['decedent_lived_in_city'] = true;
			else
			$case_profile['decedent_lived_in_city'] = false;

			$case_profile['decedent_wife_maiden_name'] = $p['decedent_wife_maiden_name'];
			$case_profile['decedent_county_residence_length'] = $p['decedent_county_residence'];
			$case_profile['decedent_fathers_full_name'] = $p['decedent_fathers_full_name'];
			$case_profile['decedent_mothers_maiden_name'] = $p['decedent_mothers_maiden_name'];
			$case_profile['branch_of_service'] = $p['branch_of_service'];
			$case_profile['date_enlisted'] = $p['date_enlisted'];
			$case_profile['date_discharged'] = $p['date_discharged'];

			$case_profile['military_serial_num'] = $p['military_serial_num'];

			if(isset($p['decedent_is_veteran']))
			$case_profile['decedent_is_veteran'] = true;
			else
			$case_profile['decedent_is_veteran'] = false;

			if(isset($p['honorable_discharge']))
			$case_profile['honorable_discharge'] = true;
			else
			$case_profile['honorable_discharge'] = false;

			if(isset($p['discharge_papers_avail']))
			$case_profile['discharge_papers_avail'] = true;
			else
			$case_profile['discharge_papers_avail'] = false;

			if(isset($p['had_policy']))
			$case_profile['had_policy'] = true;
			else
			$case_profile['had_policy'] = false;

			$case_profile['policy_with'] = $p['had_policy_with'];
			$case_profile['decedent_city'] = $p['decedent_city'];
			$case_profile['decedent_state'] = $p['decedent_state'];
			$case_profile['contact_fname'] = $p['contact_fname'];
			$case_profile['contact_mname'] = $p['contact_mname'];
			$case_profile['contact_lname'] = $p['contact_lname'];
			$case_profile['contact_address'] = $p['contact_address'];
			$case_profile['contact_city'] = $p['contact_city'];
			$case_profile['contact_state'] = $p['contact_state'];
			$case_profile['contact_zip'] = $p['contact_zip'];
			$case_profile['contact_phone'] = $p['contact_phone'];
			$case_profile['contact_email'] = $p['contact_email'];

			$case_profile['secondary_contact_name'] = $p['secondary_contact_fullname'];

			$case_profile['secondary_contact_address'] = $p['secondary_contact_address'];
			$case_profile['secondary_contact_city'] = $p['secondary_contact_city'];
			$case_profile['secondary_contact_state'] = $p['secondary_contact_state'];
			$case_profile['secondary_contact_zip'] = $p['secondary_contact_zip'];
			$case_profile['secondary_contact_phone'] = $p['secondary_contact_phone'];
			$case_profile['secondary_contact_email'] = $p['secondary_contact_email'];
			$case_profile['cemetery_name'] = $p['cemetery_name'];
			$case_profile['cemetery_address'] = $p['cemetery_address'];
			$case_profile['cemetery_city'] = $p['cemetery_city'];
			$case_profile['cemetery_state'] = $p['cemetery_state'];
			$case_profile['cemetery_zip'] = $p['cemetery_zip'];
			$case_profile['crematory_name'] = $p['crematory_name'];
			$case_profile['crematory_street'] = $p['crematory_street'];
			$case_profile['crematory_city'] = $p['crematory_city'];
			$case_profile['crematory_state'] = $p['crematory_state'];
			$case_profile['crematory_zip'] = $p['crematory_zip'];
			$case_profile['church'] = $p['church'];
			$case_profile['church_street'] = $p['church_street'];
			$case_profile['church_citystatezip'] = "{$p['church_city']}, {$p['church_state']} {$p['church_zip']}";
			$case_profile['addnl_svc'] = $p['addnl_svc'];
			$case_profile['addnl_svc_date'] = $p['addnl_svc_date'];
			$case_profile['addnl_svc_time'] = $p['addnl_svc_time'];
			$case_profile['addnl_svc_place'] = $p['addnl_svc_place'];
			$case_profile['addnl_svc_street'] = $p['addnl_svc_street'];
			$case_profile['addnl_svc_city'] = $p['addnl_svc_city'];
			$case_profile['addnl_svc_state'] = $p['addnl_svc_state'];

			# now we have the case profile built.  we can update the
			# case record.  but what fields are required?  not sure.  for now,
			# let them all in.
			$results = $cases->updateCase( $case_profile, $caseNumber );
			$this->_redirect('/index/admindashboard');
		}

		$this->view->errors = $errors;
		$caseMerchItems = $caseMerchandise->getItemsForCase( $case_num );

		$selections = array();
		$merchItems = array();
		// then filter in Casket and Vault category
		foreach( $caseMerchItems as $merch_item )
		{
			if($caseInfo['choice']=="BURIAL")
			{
				if($merch_item['item_category'] == "Casket")
				{
					$selections["Casket"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
			else
			if($caseInfo['choice']=="CREMATION")
			{
				if($merch_item['item_category'] == "Urn")
				{
					$selections["Urn"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Urn Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
		}

		$this->view->editable = true;
		$this->view->caseInfo = $case;
		$this->view->caseMerchItems = $caseMerchItems;
		$this->view->selections = $selections;
		$this->view->caseServicesItems = $caseServices->getItemsForCase( $case_num );
		$this->view->caseCashAdvanceItems = $caseCashAdvances->getItemsForCase( $case_num );

		$this->view->arranger = $rr['rows'][0];
		$this->view->home = $home;
		$this->view->case = $case;
	}

	public function admintributesAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$ks_id = $ns->ks_id;

		$this->view->user_profile = $ns->user_profile;

		$this->view->pageName = "TRIBUTEPACKAGES";
	}

	public function localetopmerchandiseAction()
	{
		$this->_helper->layout->setLayout('VAS_keystoneadmin');
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		// show admin dashboard page
		if(!$this->isLoggedIn() && !$this->isKeystoneAdmin())
		$this->_redirect('/index/login');

		$request = $this->getRequest();
		$locale_id = $request->getParam('locale_id');

		$ks_id = $ns->ks_id;

		$this->view->user_profile = $ns->user_profile;
		$this->view->locale_id = $locale_id;

		$this->view->pageName = "LOCALEMERCHANDISE";
	}

	////////////////////////////////////////////////////////////////////////
	// client-facing prereg case form method
	public function preregnewcaseAction()
	{
		$this->_helper->layout->setLayout('VAS_prereg');

		$request = $this->getRequest();

		$this->view->error = false;

		$branch_number = $request->getParam('branch_number');
		$this->view->branch = $branch_number;
		$this->view->name = 'preregnew';
		$this->view->preregcase = array();

		$homes = new FuneralHomes();

		// grab $preregcase[] from POST
		// using branch_id, look up funeral home id - locale and branch numbers too
		// add a blank case number

		$results = $homes->getHomeByFDMSId($branch_number);

		$home = $results['rows'][0];
		$this->view->home = $home;

		if($request->isPost())
		{
			$p = $request->getParams();

			$preregcase = array();

			// collect $preregcase[] from $p[]
			$preregcase['decedent_fname'] = addslashes(stripslashes($p['decedent_fname']));
			$preregcase['decedent_mname'] = addslashes(stripslashes($p['decedent_mname']));
			$preregcase['decedent_lname'] = addslashes(stripslashes($p['decedent_lname']));
			$preregcase['decedent_address'] = addslashes(stripslashes($p['decedent_address']));
			$preregcase['decedent_city'] = addslashes(stripslashes($p['decedent_city']));
			$preregcase['decedent_state'] = addslashes(stripslashes($p['decedent_state']));
			$preregcase['decedent_sex'] = addslashes(stripslashes($p['decedent_sex']));
			$preregcase['decedent_dob'] = addslashes(stripslashes($p['decedent_dob']));
			$preregcase['decedent_dod'] = addslashes(stripslashes($p['decedent_dod']));
			$preregcase['contact_fname'] = addslashes(stripslashes($p['contact_fname']));
			$preregcase['contact_mname'] = addslashes(stripslashes($p['contact_mname']));
			$preregcase['contact_lname'] = addslashes(stripslashes($p['contact_lname']));
			$preregcase['contact_address'] = addslashes(stripslashes($p['contact_address']));
			$preregcase['contact_city'] = addslashes(stripslashes($p['contact_city']));
			$preregcase['contact_state'] = addslashes(stripslashes($p['contact_state']));
			$preregcase['contact_phone'] = addslashes(stripslashes($p['contact_phone']));
			$preregcase['contact_email'] = addslashes(stripslashes($p['contact_email']));
			$preregcase['contact_relation'] = addslashes(stripslashes($p['contact_relation']));

			$preregcase['branch_id'] = $p['branch_id'];
			$preregcase['branch_number'] = $p['branch_number'];

			$preregcase['group_number'] = addslashes(stripslashes($p['group_number']));
			$preregcase['service_loc'] = addslashes(stripslashes($p['service_loc']));
			$preregcase['decedent_race'] =  addslashes(stripslashes($p['decedent_race']));
			$preregcase['decedent_birth_city'] =  addslashes(stripslashes($p['decedent_birth_city']));
			$preregcase['decedent_birth_state'] =  addslashes(stripslashes($p['decedent_birth_state']));
			$preregcase['decedent_birth_country'] =  addslashes(stripslashes($p['decedent_birth_country']));
			$preregcase['decedent_death_city'] =  addslashes(stripslashes($p['decedent_death_city']));
			$preregcase['decedent_death_state'] =  addslashes(stripslashes($p['decedent_death_state']));
			$preregcase['decedent_death_country'] =  addslashes(stripslashes($p['decedent_death_country']));
			$preregcase['death_location'] =  addslashes(stripslashes($p['death_location']));
			$preregcase['death_location_name'] =  addslashes(stripslashes($p['death_location_name']));
			$preregcase['death_location_address'] =  addslashes(stripslashes($p['death_location_address']));
			$preregcase['decedent_primary_education'] =  addslashes(stripslashes($p['decedent_primary_education']));
			$preregcase['decedent_secondary_education'] =  addslashes(stripslashes($p['decedent_secondary_education']));
			$preregcase['decedent_occupation'] =  addslashes(stripslashes($p['decedent_occupation']));
			$preregcase['decedent_business'] =  addslashes(stripslashes($p['decedent_business']));
			$preregcase['decedent_company_name'] =  addslashes(stripslashes($p['decedent_company_name']));
			$preregcase['decedent_marital_status'] =  addslashes(stripslashes($p['decedent_marital_status']));
			$preregcase['decedent_surv_spouse'] =  addslashes(stripslashes($p['decedent_surv_spouse']));
			$preregcase['decedent_wife_maiden_name'] =  addslashes(stripslashes($p['decedent_wife_maiden_name']));
			$preregcase['decedent_lived_in_city'] =  addslashes(stripslashes($p['decedent_lived_in_city']));
			$preregcase['decedent_county_residence_length'] = $p['decedent_county_residence_length'];
			$preregcase['decedent_fathers_full_name'] =  addslashes(stripslashes($p['decedent_fathers_full_name']));
			$preregcase['decedent_mothers_maiden_name'] =  addslashes(stripslashes($p['decedent_mothers_maiden_name']));
			$preregcase['decedent_is_veteran'] =  addslashes(stripslashes($p['decedent_is_veteran']));
			$preregcase['branch_of_service'] =  addslashes(stripslashes($p['branch_of_service']));
			$preregcase['date_enlisted'] =  addslashes(stripslashes($p['date_enlisted']));
			$preregcase['date_discharged'] =  addslashes(stripslashes($p['date_discharged']));
			$preregcase['honorable_discharge'] =  addslashes(stripslashes($p['honorable_discharge']));
			$preregcase['military_serial_num'] =  addslashes(stripslashes($p['military_serial_num']));
			$preregcase['discharge_papers_avail'] =  addslashes(stripslashes($p['discharge_papers_avail']));
			$preregcase['had_policy'] =  addslashes(stripslashes($p['had_policy']));
			$preregcase['policy_with'] =  addslashes(stripslashes($p['policy_with']));

			// see if it be kosher, mofo
			$preregForm = new PreregCaseForm();
			if($preregForm->isValid($preregcase))
			{
				// create a new case record with the stuff found in this form.
				$cases = new FDMSCases();

				$preregcase['branch_num'] = $home['branch_number'];
				$preregcase['FDMS_case_num'] = '';
				$preregcase['FDMS_vitals_id'] = -1;
				$preregcase['FDMS_funeral_director_id'] = -1;
				$preregcase['status'] = 'PREREG';

				$cases->insert( $preregcase );

				$this->_redirect('/index/preregthankyou');
			}
		}
	}

	public function preregthankyouAction()
	{
		$this->_helper->layout->setLayout('VAS_prereg');
	}

	/////////////////////// Funeral Director/Arranger dashboard actions
	//*********************************************************************
	// Funeral Director/Arrangers Dashboard
	public function fddashboardAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		/*$fdIdsStr = $ns->user_profile['FD_ids'];
		$fdBranchesStr = $ns->user_profile['branchnums'];

		$fdIds = explode(",",$fdIdsStr);
		$fdBranches = explode(",", $fdBranchesStr);

		$FDMS_cases = array();
		$FDMS_ids = array();
		$FDMS_branchnums = array();

		$groupsModel = new VASGroups();

		$group_ids = $groupsModel->groupIdsForBranchIds( $fdBranches );
		if(null !== $group_ids) {
		$this->view->group_ids = $group_ids;
		$this->view->group_ids_str = "".implode(",",$group_ids)."";
		}
		$numFDids = count($fdIds);
		$numFDbranches = count($fdBranches);

		//foreach( $fdIds as $fdId )
		for( $i=0; $i<$numFDids; $i++ )
		{
		// get branch number
		$fdId = $fdIds[$i];
		$branchNum = $fdBranches[$i];

		$results = FDMSAPIcalls::getCasesForDirector( $fdId );
		$caseSummaries = $results['rows'];
		foreach($caseSummaries as $summary)
		{
		$vitalsId = $summary['FDMS_vitals_id'];
		$FDMS_cases[$vitalsId] = $summary["FDMS_case_num"];
		$FDMS_ids[$vitalsId] = $fdId;
		$FDMS_branchnums[$vitalsId] = $branchNum;
		}
		}

		// now load FDMS case numbers that we already have in VAS
		$casesModel = new FDMSCases();
		$VAS_cases = array();
		$results = $casesModel->getFDMSCaseNumbersForFuneralDirIds( $fdIdsStr );
		foreach( $results['rows'] as $row )
		{
		$VAS_cases[$row['FDMS_vitals_id']] = $row['FDMS_case_num'];
		}

		// now diff them to get ones in FDMS but not in VAS
		$new_cases = array_diff( $FDMS_cases, $VAS_cases );

		foreach( $new_cases as $vitalsId=>$caseNum )
		{
		$results = FDMSAPIcalls::getCaseDetails( $vitalsId );
		if(count($results['rows'])>0)
		{
		$caseInfo = $results['rows'][0];
		$isTrade = (false !== stripos($caseInfo['sale_type'], "Trade"));
		$isShipping = (false !== stripos($caseInfo['sale_type'], "Shipping"));
		if($isTrade || $isShipping) continue;

		try
		{
		//					echo "inserting<br>";
		$caseInfo['status'] = 'OPEN';
		$caseInfo['FDMS_funeral_director_id'] = $FDMS_ids[$vitalsId];
		$caseInfo['branch_num'] = $FDMS_branchnums[$vitalsId];
		$casesModel->insert( $caseInfo );
		}
		catch(Exception $e)
		{
		echo "".$e."<br>";
		}
		}
		}*/
		//		exit(0);

		// set up info for the views
		$this->view->user_profile = $ns->user_profile;
		$this->view->FD_license_number = $ns->user_profile['FDMS_license_number'];
		$this->view->pageName = "FD_DASHBOARD";
	}

	public function fdmatchpreregcasesAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		$fdid = $ns->fd_id;
		$fhid = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$funeral_dir_id = $req->getParam('funeral_dir_id');

		$casesModel = new FDMSCases();

		$fdIDlist = $ns->user_profile['FD_ids'];

		$fdBranchesListRaw = $ns->user_profile['branches'];

		$this->view->user_profile = $ns->user_profile;

		$branches = explode( ",", $fdBranchesListRaw );
		$branchList = array();
		foreach($branches as $branch)
		$branchesList[] = "'$branch'";
		$fdBranchesList = implode(",",$branchesList);

		if($req->isPost())
		{
			// capture list of checked prereg cases and remove them
			// from the db. (actually, set status to 'CLAIMED') then
			// redirect to /index/fddashboard
			$preregcases = $req->getParam('preregcases');

			$preregcases_str = implode(",", $preregcases);
			$results = $casesModel->markPreregCasesAsClaimed( $preregcases_str );

			$this->_redirect('/index/fddashboard');
		}

		$results = $casesModel->getPreregCasesForBranches( $fdBranchesList );
		$this->view->preregCases = $results['rows'];

		$results = $casesModel->getOpenCasesForFDMSFuneralDirIds( $fdIDlist );
		$this->view->pendingCases = $results['rows'];

		$results = $casesModel->getFinishedCasesForFDMSFuneralDirIds( $fdIDlist );
		$this->view->finishedCases = $results['rows'];
	}

	// 2. review a preregistration case
	public function reviewpreregcaseAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		// get personalization and profile info
		$this->view->username = $ns->username;
		$this->view->permissions = $this->_permissions;
		$this->view->funeralDirectorProfile = $ns->user_profile;

		// get funeral home profile info
		$funeral_homes = new FuneralHomes();
		$fhid = $this->_fh_id;

		//FIXME - make sure to use the branch_number one instead of our VAS id
		$this->view->funeral_home = $funeral_homes->get_profile( $fhid );

		// get case id from params
		$req = $this->getRequest();
		$case_id = $req->getParam('case_id');
	}

	// *** here is where the FD enters the VAS module sequence ***
	public function opencaseAction()
	{
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		if(!$this->isLoggedIn())
		{
			// add flash message TEO "Cannot access cases unless you are logged in"
			$this->_redirect('/index/login');
		}

		$req = $this->getRequest();

		// get the case FDMS vitals ID for the case we're hitting VAS on
		$caseVitalsId = $req->getParam('vitalsId');

		// load the case data and assign it to $ns->caseData

		// look up the last module completed (e.g., $caseData["lastModule"]
		// get the next module in sequence, and route to that module (action).

	}

	// 4. review finished case
	public function finishedcaseAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');
		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		// get finished case with given id
		$req = $this->getRequest();

		// get the case FDMS vitals ID for the case we're hitting VAS on
		$case_num = $req->getParam('case_number');
		if(empty($case_num))
		{
			// case# is empty.  redirect where?
		}

		$casesModel = new FDMSCases();

		$results = $casesModel->getCaseInfoForFDMSCaseNum( $case_num );
		$caseInfo = $results['rows'][0];

		$case_branch = $caseInfo['branch_num'];

		$funeralHomesModel = new FuneralHomes();
		$results = $funeralHomesModel->getHomeByFDMSId( $case_branch );
		$home_info = $results['rows'][0];

		# need to get arrange
		$users = new Users();

		$fdId = $caseInfo['FDMS_funeral_director_id'];

		$results = $users->getFuneralDirectorForFDMSId( $fdId );
		$caseFDinfo = $results['rows'][0];

		$caseServices = new CaseServices();
		$caseCashAdvances = new CaseCashAdvances();
		$caseMerchandise = new CaseMerchandise();

		$caseMerchItems = $caseMerchandise->getItemsForCase( $case_num );

		$selections = array();
		$merchItems = array();
		// then filter in Casket and Vault category
		foreach( $caseMerchItems as $merch_item )
		{
			if($caseInfo['choice']=="BURIAL")
			{
				if($merch_item['item_category'] == "Casket")
				{
					$selections["Casket"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
			else
			if($caseInfo['choice']=="CREMATION")
			{
				if($merch_item['item_category'] == "Urn")
				{
					$selections["Urn"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Urn Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
		}

		$this->view->readonlyfields = "READONLY";
		$this->view->caseMerchItems = $merchItems;
		$this->view->selections = $selections;
		$this->view->caseServicesItems = $caseServices->getItemsForCase( $case_num );
		$this->view->caseCashAdvanceItems = $caseCashAdvances->getItemsForCase( $case_num );
		// now see if $case_branch is in one of the branches the $ns->user_info
		// works at.  if not, redirect where?

		// look up the case info and assign it to $this->view->case
		// look up the home for the case and assign it to $this->view->home

		$this->view->case = $caseInfo;
		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $caseFDinfo;
		$this->view->home = $home_info;
		$this->view->user_profile = $ns->user_profile;
		$this->view->show_printable_itinerary = true;
		echo $this->view->render( 'index/reviewcase.phtml' );
	}

	public function printableintineraryAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');

		$ns = new Zend_Session_Namespace("VAS");

		if(!isset($ns->user_profile))
		$this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$p = $this->getParams();
		$case_number = $p['case_number'];

		// need models for each of the things making up the case that we need:
		// case data
		// funeral home data
		// funeral arranger data
		// cash advances
		$casesModel = new FDMSCases();
		$results = $casesModel->getCase($case_number);

		if($results['status'] == "SUCCEEDED")
		{
			$caseInfo = $results['rows'][0];

			//1 - copy the vasclosing.phtml formatting
			//2 -
		}
		else
		{
		}
	}

	// 5. FD account profile.
	public function fdmyaccountAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');

		$ns = new Zend_Session_Namespace("VAS");

		if(!isset($ns->user_profile))
		$this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$fdid = $ns->user_profile['id'];

		$users = new Users();

		$dstFilename = "";
		$dstPath = "";

		$branches = $ns->user_profile['branchnums'];
		$branch_list = explode(",", $branches);
		foreach( $branch_list as &$branch )
		$branch = "'$branch'";
		$branches_str = implode(",", $branch_list);

		$funeralHomesModel = new FuneralHomes();

		$results = $funeralHomesModel->getFuneralHomesForBranchList($branches_str);
		$branches_array = $results['rows'];
		$this->view->homes = $branches_array;
		$this->view->pageName = "FDPROFILE";

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getPost();

			$posted_fd_profile = array();

			//$posted_fd_profile["username"] = $p["username"];
//			$posted_fd_profile["password"] = $p["password"];
			$posted_fd_profile["full_name"] = $p["full_name"];
			$posted_fd_profile["fname"] = $p["fname"];
			$posted_fd_profile["mname"] = $p["mname"];
			$posted_fd_profile["lname"] = $p["lname"];
			//			$posted_fd_profile["address"] = $p["address"];
			//			$posted_fd_profile["city"] = $p["city"];
			//			$posted_fd_profile["state"] = $p["state"];
			//			$posted_fd_profile["zip"] = $p["zip"];
			$posted_fd_profile["phone"] = $p["phone"];
			$posted_fd_profile["email"] = $p["email"];
			//			$posted_fd_profile["FDMS_license_number"] = $p["FDMS_license_number"];
			$license_num = $p["FDMS_license_number"];

			// get file transfer adapter to let us upload the FD's new profile picture
			$upload = new Zend_File_Transfer_Adapter_Http();
			$upload->setDestination(ROOT_DIR."/upload/");
			try {

				// upload received file(s)
				if($upload->receive($p['photo']))
				{
					// make sure we *have* a srcPath.
					$srcPath = $upload->getFileName();
					if(!empty($srcPath))
					{
						// split the uploaded (temp) filename into parts so we can rename it
						$parts = pathinfo($srcPath, PATHINFO_DIRNAME|PATHINFO_BASENAME|PATHINFO_EXTENSION|PATHINFO_FILENAME);

						$srcExt = $parts['extension'];
						$srcFilename = $parts['filename'];
						$dstFilename = "FD_{$fdid}_profile_pic.{$srcExt}";

						$dstPath =  ARTWORK_DIR."/FD/$dstFilename";

						if(copy( $srcPath, $dstPath))
						$posted_fd_profile['photo'] = $dstFilename;
					}
					else
					{
						// photo path is empty, which means it didn't get filled
						// from the FD profile page.  leave the one in the db alone.
						if(empty($posted_fd_profile['photo']))
						$posted_fd_profile['photo'] = $ns->user_profile['photo'];
					}
				}
			}
			catch (Zend_File_Transfer_Exception $e)
			{
				echo $e->getMessage();
				$posted_fd_profile['photo'] = $ns->user_profile['photo'];
			}

			// update fd user record
			$users->updateFDMSFDUser( $posted_fd_profile, $license_num );

			// and reload it for $license_num
			$result = $users->getFuneralDirectorForFDMSLicenseNum( $license_num );
			$user_profile = $result['rows'][0];
			$ns->user_profile = $user_profile;

			$this->view->user_profile = $ns->user_profile;

			$rendered_fd_profile_form = $this->view->render('index/funeraldirector_accountform.phtml');
		}
		else
		{
			// #1 - get list of branches from $ns->user_profile['branches']
			// #2 - get list of funeral home details for those branches
			// #3 - assign it to $this->view->branches

			$this->view->user_profile = $ns->user_profile;

			$picture_name = $this->view->user_profile['photo'];
			//$rendered_fd_profile_form = $this->view->render('index/funeraldirector_accountform.phtml');
		}

	}

	// 7. FAQ/Help page display action
	public function fdfaqhelpAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$fdid = $this->_fd_id;
		$funeral_directors = new FuneralDirectors();

		$results = $funeral_directors->getProfileForDirectorByVASId($fdid);
		$this->view->fd_profile = $results['rows'][0];
		$this->view->fh_profile = $ns->funeral_home;

		echo $this->view->render('index/funeraldirector_faqhelp.phtml');
	}

	public function fdcaterersAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');
		$request = $this->getRequest();

		$ns = new Zend_Session_Namespace("VAS");

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$this->view->user_profile = $ns->user_profile;

		// list of branches this FD can work at
		$branches = explode(",", $this->view->user_profile['branchnums'] );

		$vendors = new Vendors();
		$vendorProducts = new VendorProducts();
		$funeralHomes = new FuneralHomes();

		$branchesArray = $funeralHomes->getInfoOnTheseBranches( $branches );
		$this->view->branches = $branchesArray['rows'];

		$this->view->branch_number = $this->view->branches[0]['branch_number'];
		$this->view->current_branch = $this->view->branches[0]['branch_number'];

		$this->view->pageName = "CATERERS";
		$this->view->caterers = $caterers;
		$this->view->menus = $menus;
	}

	public function fdfloralAction()
	{
		$this->_helper->layout->setLayout('VAS_funeraldirector');
		$request = $this->getRequest();

		$ns = new Zend_Session_Namespace("VAS");

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$this->view->user_profile = $ns->user_profile;

		// list of branches this FD can work at
		$branches = explode(",", $this->view->user_profile['branchnums'] );
		$funeralHomes = new FuneralHomes();
		$branchesArray = $funeralHomes->getInfoOnTheseBranches( $branches );
		$this->view->branches = $branchesArray['rows'];
		$this->view->branch_number = $this->view->branches[0]['branch_number'];
		$this->view->current_branch = $this->view->branches[0]['branch_number'];

		$this->view->pageName = "FLORISTS";
		$this->view->caterers = $caterers;
		$this->view->menus = $menus;

	}

	//<<<<<<<<<<<<<<<<<<< VAS MODULE ACTIONS >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
	// need to make this a little smarter.
	public function nextModule( &$modules, $curModule )
	{
		if(null == $modules) return "_FAIL_";

		$keyIdx = array_search( $curModule, $modules );
		if(false === $keyIdx) return "_FAIL_";
		if($keyIdx == count($modules)-1) return "_END_";

		// get the next module key
		$nextModuleKey = $modules[$keyIdx+1];
		if($curModule == "BURIAL")
		{
			if($nextModuleKey == "CASKET")
			{
				return $nextModuleKey;
			}
			else
			{
				// skip next three
				$keyIdx += 5;
				return $modules[$keyIdx];
			}
		}
		else
		if($curModule == "CASKET")
		{
			if($nextModuleKey == "BURIAL")
			{
				return $nextModuleKey;
			}
			else
			{
				// skip next three
				$keyIdx += 5;
				return $modules[$keyIdx];
			}
		}
		else
		if($curModule == "CREMATION")
		{
			if($nextModuleKey == "URN")
			{
				return $nextModuleKey;
			}
			else
			{
				// skip next
				$keyIdx += 3;
				return $modules[$keyIdx];
			}
		}
		else
		if($curModule == "URN")
		{
			if($nextModuleKey == "CREMATION")
			{
				return $nextModuleKey;
			}
			else
			{
				// skip next
				$keyIdx += 3;
				return $modules[$keyIdx];
			}
		}
		else
		if($curModule == "MEMORIAL")
		{
			$keyIdx += 2;
			return $modules[$keyIdx];
		}

		// now deal with "NONE" modules
		$moduleCount = count($modules);
		$j = $keyIdx + 1;
		while( $j<$moduleCount && $modules[$j] == "NONE" ) $j++;
		$j--;
		$keyIdx = $j;

		return $modules[ $keyIdx + 1 ];
	}

	private function breadcrumb_find( $breadcrumbs, $pageKey )
	{
		$idx = 0;
		if(null == $breadcrumbs) return -1;
		foreach( $breadcrumbs as $crumb )
		{
			if($crumb['key'] == $pageKey)
			{
				$elidx = $idx;
				return $idx;
			}
			$idx++;
		}

		return -1;
	}

	private function breadcrumb_push( $breadcrumbs, $pageKey )
	{
		// look up controller name for $pageKey
		// if found, make tuple and push
		if($this->breadcrumb_find( $breadcrumbs, $pageKey)>=0)
		return $breadcrumbs;

		if(isset(VASProcessModules::$_modules[$pageKey]))
		{
			$pageModule = VASProcessModules::$_modules[$pageKey];
			$pageModuleAction = $pageModule[1];
			$title = $pageModule[0];
			$breadcrumbs[] = array( 'key'=>$pageKey, 'url'=>"/index/$pageModuleAction", 'label'=>$title );
		}

		return $breadcrumbs;
	}

	private function breadcrumb_pop_prior( $breadcrumbs, $pageKey )
	{
		$idx = $this->breadcrumb_find( $breadcrumbs, $pageKey );
		if($idx>=0)
		{
			$newbreadcrumbs = array();
			for( $i=0; $i<$idx; $i++ )
			{
				$crumb = $breadcrumbs[$i];
				$newbreadcrumbs[] = $crumb;
			}
			return $newbreadcrumbs;
		}

		return $breadcrumbs;
	}

	// method to test module order specification
	public function testmoduleorderAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		$request = $this->getRequest();

		$FDMS_license_number = $request->getParam('license_number');

		$users = new Users();
		$results = $users->getFuneralDirectorForFDMSLicenseNum( $FDMS_license_number );

		if($results['status'] != "SUCCEEDED" )
		{
			Zend_Debug::dump($results);

			exit(0);
		}

		$profile = $results['rows'][0];

		$modules = explode( "|", $profile['modules'] );

		// whole thrust of this is to output module order for BURIAL and CREMATION choices
		// sequence 1 -
		$page = "INTRO";
		$nextPage = $this->nextModule( $modules, $page ); echo "$page -> $nextPage<br>"; $page = $nextPage;
		$nextPage = $this->nextModule( $modules, $page ); echo "$page -> $nextPage<br>"; $page = $nextPage;
		$nextPage = $this->nextModule( $modules, $page ); echo "$page -> $nextPage<br>"; $page = $nextPage;
		$choicesPage = $page;

		// hmm.  from CHOICES, we do this:
		// if they picked BURIAL, we go to page number five in the modules list
		// if they picked CREMATION, we go to page number seven in the modules list


	}

	public function testbreadcrumbsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$breadcrumbs = array();

		$this->breadcrumb_push( $breadcrumbs, "INTRO" );
		$this->breadcrumb_push( $breadcrumbs, "EXPECT" );
		$this->breadcrumb_push( $breadcrumbs, "LIFE" );
		$this->breadcrumb_push( $breadcrumbs, "CHOICES" );

		echo "stack 1 after pushing INTRO, EXPECT, and CHOICES<br>";
		Zend_Debug::dump($breadcrumbs);

		$breadcrumbs = $this->breadcrumb_pop_prior( $breadcrumbs, "CHOICES" );

		echo "<p>stack 2 after popping down below CHOICES<br>";
		Zend_Debug::dump($breadcrumbs);

		$this->breadcrumb_push( $breadcrumbs, "CHOICES" );

		echo "<p>stack 3 after pushing CHOICES<br>";
		Zend_Debug::dump($breadcrumbs);

		$breadcrumbs = $this->breadcrumb_pop_prior( $breadcrumbs, "EXPECT" );

		echo "<p>stack 2 after popping down below EXPECT<br>";
		Zend_Debug::dump($breadcrumbs);

		$breadcrumbs = $this->breadcrumb_pop_prior( $breadcrumbs, "INTRO" );

		echo "<p>stack 2 after popping down below INTRO<br>";
		Zend_Debug::dump($breadcrumbs);

		$this->breadcrumb_push( $breadcrumbs, "INTRO" );
		$this->breadcrumb_push( $breadcrumbs, "EXPECT" );
		$this->breadcrumb_push( $breadcrumbs, "LIFE" );
		$this->breadcrumb_push( $breadcrumbs, "CHOICES" );

		echo "<p>stack 2 after pushsing EXPECT, LIFE, and CHOICES<br>";
		Zend_Debug::dump($breadcrumbs);
	}

	private function make_breadcrumbs( $keys_str )
	{
		$keys = explode(",", $keys_str);
		$breadcrumbs = array();
		foreach( $keys as $pageKey )
		{
			if(isset(VASProcessModules::$_modules[$pageKey]))
			{
				$pageModule = VASProcessModules::$_modules[$pageKey];
				$pageModuleAction = $pageModule[1];
				$pageModuleTitle = $pageModule[0];
				$newpage = array( 'key'=>$pageKey,
				'url'=>"/index/$pageModuleAction",
				'label'=>$pageModuleTitle );
				$breadcrumbs[] = $newpage;
			}
		}

		return $breadcrumbs;
	}

	private function save_breadcrumbs( $breadcrumbs )
	{
		$keys = array();
		foreach( $breadcrumbs as $crumb )
		$keys[] = $crumb['key'];
		return implode(",", $keys );
	}

	public function vasprevpageAction()
	{
		// turn off rendering since this is just a dispatch method
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		// bring session into memory
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$current_page = $req->getParam('current_page');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;

		# now take $caseInfo['breadcrumbs'] and backtrack one level
		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $current_page );
		$breadcrumbs_top = count($breadcrumbs)-1;
		if($breadcrumbs_top<0)
		{
			$this->_redirect('/index/fddashboard');
		}
		else
		{
			$prevModule = $breadcrumbs[$breadcrumbs_top];
			$prevModuleKey = $prevModule['key'];
			$prevPModule = VASProcessModules::$_modules[$prevModuleKey];
			$prevModuleAction = $prevPModule[1];
			$actionToGoTo = "/index/$prevModuleAction";
			$this->_redirect($actionToGoTo);
		}
	}

	public function entervasAction()
	{
		// turn off rendering since this is just a dispatch method
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		// bring session into memory
		$ns = new Zend_Session_Namespace( "VAS" );

		// if nobody is logged in bouce to /index/login
		// if logged in but admin bounce to /index/admindashboard

		// 1. parameter is case_id
		$req = $this->getRequest();
		// if case_id is empty, bounce to /index/fddashboard

		$case_num = $req->getParam('FDMS_case_num');
		$ns->case_num = $case_num;

		$cases = new FDMSCases();
		$users = new Users();
		$homes = new FuneralHomes();

		// get case info for case referenced on entry
		$results = $cases->getCaseInfoForFDMSCaseNum( $case_num );
		$caseInfo = $results['rows'][0];

		// get branch this case is attached to
		$branchId = $caseInfo['branch_num'];
		$localeId = $caseInfo['locale_id'];

		$fdId = $caseInfo['FDMS_funeral_director_id'];

		$results = $users->getFuneralDirectorForFDMSId( $fdId );
		$caseFDinfo = $results['rows'][0];
		$FDMS_license_number = $caseFDinfo['FDMS_license_number'];

		$results = $homes->getHomeByFDMSId($branchId);

		$caseFHinfo = $results['rows'][0];

		$ns->caseNum = $case_num;
		$ns->caseInfo = $caseInfo;
		$ns->caseFHinfo = $caseFHinfo;
		$ns->caseFDinfo = $caseFDinfo;

		$caseMerch = new CaseMerchandise();
		$caseServices = new CaseServices();
		$caseCashAdvances = new CaseCashAdvances();

		$ns->merchandise = $caseMerch->getItemsForCase( $case_num );
		$ns->services = $caseServices->getItemsForCase( $case_num );
		$ns->cashadvances = $caseCashAdvances->getItemsForCase( $case_num );

		$modules = $caseFDinfo['modules'];
		if(empty($modules))
		{
			$modules = VASProcessModules::getDefaultOrder();
			$users->setModulesForFuneralDirector( $modules, $FDMS_license_num );
		}

		$ns->modules = explode("|", $modules);

		$currentModuleKey = $caseInfo['current_module'];
		if(""==$currentModuleKey)
		$currentModuleKey = "INTRO";

		$breadcrumbs_str = $caseInfo['breadcrumbs'];
		$breadcrumbs = $this->make_breadcrumbs( $breadcrumbs_str );
		$ns->breadcrumbs = $breadcrumbs;

		$currentModule = VASProcessModules::$_modules[$currentModuleKey];
		$currentModuleAction = $currentModule[1];

		$ns->currentModuleKey = $currentModuleKey;

		$actionToGoTo = "/index/$currentModuleAction";

		$this->_redirect($actionToGoTo);
	}

	public function vassaveandexitAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$cases = new FDMSCases();

		if(isset($ns->entryTime))
		{
			$moduleTimes = new VASModuleTimes();
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);
		}

		$results = $cases->updateCurrentModuleForFDMSVitalsId( $ns->currentModuleKey, $ns->caseInfo['FDMS_vitals_id']);

		$breadcrumbs_str = $this->save_breadcrumbs( $ns->breadcrumbs );
		$profile = array('breadcrumbs'=>$breadcrumbs_str);
		$results = $cases->updateCase( $profile, $case_num );
		unset( $ns->breadcrumbs );

		$this->_redirect('/index/fddashboard');
	}

	public function vasintroductionAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "INTRO";

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];

		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$this->view->moduleAction = $actionURL;

		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "EXPECT";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );

		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();

		if($req->isPost())
		{
			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );

			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$ns->breadcrumbs = $breadcrumbs;

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Introduction";
		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vaswhattoexpectAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "EXPECT";
		$caseInfo["current_module"] = $ns->currentModuleKey;
		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];

		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$this->view->moduleAction = $actionURL;

		$moduleTimes = new VASModuleTimes();

		//FIXME - make this $nextModuleKey = $this->nextModule( $this->modules, $ns->currentModuleKey );
		//		$nextModuleKey = "LIFE";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		//		echo "{$ns->currentModuleKey} -> $nextModuleKey1 ";

		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );
		//$breadcrumbs = $ns->breadcrumbs;

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "What to Expect";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page
		$ns->entryTime = time();
	}

	public function vascelebrationoflifeAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "LIFE";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];

		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$this->view->moduleAction = $actionURL;
		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "CHOICES";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		//		echo "{$ns->currentModuleKey} -> $nextModuleKey1 ";
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Celebration of Life";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vaschoicesAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$cases = new FDMSCases();
		$this->view->currentVASpage = "CHOICES";
		$ns->currentModuleKey = "CHOICES";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];

		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$this->view->moduleAction = $actionURL;
		$moduleTimes = new VASModuleTimes();

		$emptyArray = array();

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// also need to zero out, for this case, the merch/services/cash advances
			$caseMerch = new CaseMerchandise();
			$caseMerch->setItemsForCase( $emptyArray, $case_num, true );

			$caseServices = new CaseServices();
			$caseServices->setItemsForCase( $emptyArray, $case_num, true );

			$caseCashAdv = new CaseCashAdvances();
			$caseCashAdv->setItemsForCase( $emptyArray, $case_num, true );

			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			// get value of choice user made in this page.  if it's burial, jump to the burial page.
			// if it's cremation, jump to the cremation page.
			$choice = $req->getParam("choice");
			if($choice == "BURIAL")
			{
				//				$nextModuleKey = "BURIAL";
				$nextModuleKey = $ns->modules[4];
				$ns->caseInfo['decedent_sale_type'] = "At-Need Burial";
			}
			else
			if($choice == "CREMATION")
			{
				//				$nextModuleKey = "CREMATION";
				$nextModuleKey = $ns->modules[6];
				$ns->caseInfo['decedent_sale_type'] = "At-Need Cremation";
			}
			else
			if($choice == "MEMORIAL")
			{
				$nextModuleKey = "MEMORIAL";
				$ns->caseInfo['decedent_sale_type'] = "At-Need Cremation";
			}

			// record $choice in case record
			$results = $cases->setChoiceForCase( $choice, $case_num );

			$ns->caseInfo['choice'] = $choice;

			// get action for next module and execute it
			$nextModule = VASProcessModules::$_modules[$nextModuleKey];
			$nextModuleAction = $nextModule[1];

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Choices";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasburialAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );
		$req = $this->getRequest();

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "BURIAL";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		if(!$caseFHinfo['show_packages'])
		{
			// 1. can't show tributes, so we need to do the following:
			//    a. get next module action
			$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
			$nextModule = VASProcessModules::$_modules[$nextModuleKey];
			$nextModuleAction = $nextModule[1];
			//	  b. add it to session cache as "return_address"
			$ns->return_address = $nextModuleAction;
			//	  c. redirect to vasalacarteAction
			$this->_redirect('/index/vasalacarte');
		}

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		// get the available FDMS burial tributes for this locale
		$results = FDMSAPIcalls::getBurialTributesForLocaleId( $locale_id );

		$rows = $results['rows'];
		$tributes = array();
		foreach($rows as $row)
		$tributes[$row['package_id']] = $row['package_type'];

		$this->view->tributes = $tributes;

		//		$nextModuleKey = "CASKET";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		// need to collect tribute name too.
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$selected_tribute_id = $req->getParam('tribute');
			$selected_tribute_name = $tributes[$selected_tribute_id];

			$caseInfo['tribute_chosen'] = $selected_tribute_name;
			$ns->caseInfo = $caseInfo;

			$profile = array( 'tribute_chosen'=>$selected_tribute_name );

			$casesModel = new FDMSCases();
			$casesModel->updateCase( $profile, $case_num );

			$results = FDMSAPIcalls::getPackageDetailsForPackageId( $selected_tribute_id, $locale_id );
			if($results['status'] != "SUCCEEDED")
			{
				// if we blew chow getting this, add a message and redisplay the page
			}

			// otherwise, capture items and dump them for the moment
			// look up items in package using FDMS API
			$details = $results['rows'];

			// sift through the $details and pick out the merchandise, services, and
			// cash advances so we can put them into the right cart table
			$cart_merchandise = array();
			$cart_services = array();
			$cart_cashadvances = array();

			foreach( $details as $pkg_item )
			{
				$pkg_item['source'] = $selected_tribute_name;
				$category = $pkg_item['item_category'];
				if($category == "SRV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_services[] = $pkg_item;
				}
				else
				if($category == "ADV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_cashadvances[] = $pkg_item;
				}
				else
				if($category == "OTR")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_merchandise[] = $pkg_item;
				}
			}

			//			echo "setting merchandise into shopping cart...<br>";
			$caseMerch = new CaseMerchandise();
			$caseMerch->setItemsForCase( $cart_merchandise, $case_num );

			//			echo "Merchandise in cart:<br>";
			//			$merch2 = $caseMerch->getItemsForCase( $case_num );
			//			Zend_Debug::dump($merch2);
			//			exit(0);

			//			echo "setting services into shopping cart...<br>";
			$caseServices = new CaseServices();
			$caseServices->setItemsForCase( $cart_services, $case_num );

			//			echo "Services in cart:<br>";
			//			$srv2 = $caseServices->getItemsForCase( $case_num );
			//			Zend_Debug::dump($srv2);

			//			echo "setting cash advances into shopping cart...<br>";
			$caseCashAdvances = new CaseCashAdvances();
			$caseCashAdvances->setItemsForCase( $cart_cashadvances, $case_num );

			//			echo "Cash advances in cart:<br>";
			//			$adv2 = $caseCashAdvances->getItemsForCase( $case_num );
			//			Zend_Debug::dump($adv2);

			// record exit from module

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$tributesModel = new TributePackages();
		$bullet_points = array();
		foreach( $tributes as $id=>$type )
		{
			$bullet_points[$type] = array();
			$results = $tributesModel->getBulletPointsForTribute( $type );
			if($results['status']=="SUCCEEDED")
			{
				$bpXMLstr = $results['rows'][0]['bigxml'];
				$bpXML = simplexml_load_string( $bpXMLstr );
				foreach( $bpXML->bulletpoint as $bp )
				{
					$bullet_points[$type][] = "".$bp->name;
				}
			}
		}
		$this->view->bullet_points = $bullet_points;

		$this->view->title = "Burial Tributes";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		$ns->entryTime = time();
	}

	public function vascasketAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "CASKET";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "SERVICES";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		// get list of caskets and vaults from FDMS.  as a placeholder, put up two SELECT menus
		// - one for caskets, one for vaults - and pick from that.
		$results = FDMSAPIcalls::getCasketsAndVaultsBranchNumber( $branch_num );
		$caskets = array();
		$vaults = array();

		foreach( $results['rows'] as $inventory_item )
		{
			if($inventory_item['item_category'] == "Casket")
			{
				$caskets[$inventory_item['inventory_master_id']] = $inventory_item;
			}
			else
			if($inventory_item['item_category'] == "Vault")
			{
				$vaults[$inventory_item['inventory_master_id']] = $inventory_item;
			}
		}

		$caseMerchandise = new CaseMerchandise();

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;
			$casket_kmnumber = $req->getParam('casket_number');
			$vault_kmnumber = $req->getParam('vault_number');

			# FIXME - do a regex on KM#
			$casket_id = -1;
			foreach($caskets as $cid=>$casket)
			{
				#				echo "checking casket $casket_kmnumber with {$casket['item_description']}<br>";
				if(false !== strpos($casket['item_description'], $casket_kmnumber))
				{
					$casket_id = $cid;
				}
			}

			$vault_id = -1;
			foreach($vaults as $vid=>$vault)
			{
				#				echo "checking vault $vault_kmnumber with {$vault['item_description']}<br>";
				if(false !== strpos($vault['item_description'], $vault_kmnumber))
				{
					$vault_id = $vid;
				}
			}
			// add chosen casket to case merchandise table
			$casketForTable = array();

			if($casket_id != -1)
			{
				$selectedCasket = $caskets[$casket_id];

				$casketForTable['price_list_id'] = $selectedCasket['inventory_master_id'];
				$casketForTable['item_category'] = "Casket";
				//			$casketForTable['item_name'] = $selectedCasket['item_name'];
				$casketForTable['line_number'] = $selectedCasket['line_number'];
				$casketForTable['item_description'] = $selectedCasket['item_description'];
				$casketForTable['item_amount'] = $selectedCasket['item_amount'];
				$casketForTable['qty'] = 1;
				$casketForTable['total'] = $casketForTable['item_amount'];
				$casketForTable['FDMS_case_num'] = $case_num;
				$casketForTable['source'] = "Casket Showroom";
			}
			else
			{
				$casketForTable['price_list_id'] = -1;
				$casketForTable['item_category'] = "Casket";
				//			$casketForTable['item_name'] = $selectedCasket['item_name'];
				$casketForTable['line_number'] = -1;
				$casketForTable['item_description'] = "Description of $casket_kmnumber description not available from FDMS";
				$casketForTable['item_amount'] = -1;
				$casketForTable['qty'] = 0;
				$casketForTable['total'] = -1;
				$casketForTable['FDMS_case_num'] = $case_num;
				$casketForTable['source'] = "Casket Showroom";
			}
			// qty, total, FDMS_case_num, source

			// add chosen vault to case merchandise table
			$vaultForTable = array();
			if($vault_id != -1)
			{
				$selectedVault = $vaults[$vault_id];

				$vaultForTable['price_list_id'] = $selectedVault['inventory_master_id'];
				$vaultForTable['item_category'] = "Casket Vault";
				//$vaultForTable['item_name'] = $selectedVault['item_name'];
				$vaultForTable['line_number'] = $selectedVault['line_number'];
				$vaultForTable['item_description'] = $selectedVault['item_description'];
				$vaultForTable['item_amount'] = $selectedVault['item_amount'];
				$vaultForTable['qty'] = 1;
				$vaultForTable['total'] = $vaultForTable['item_amount'];
				$vaultForTable['FDMS_case_num'] = $case_num;
				$vaultForTable['source'] = "Casket Showroom";
			}
			else
			{
				$vaultForTable['price_list_id'] = -1;
				$vaultForTable['item_category'] = "Casket Vault";
				//$vaultForTable['item_name'] = "Not available";
				$vaultForTable['line_number'] = -1;
				#				$vaultForTable['item_description'] = "Not available";
				$vaultForTable['item_description'] = "Description of $vault_kmnumber description not available from FDMS";
				$vaultForTable['item_amount'] = -1;
				$vaultForTable['qty'] = 0;
				$vaultForTable['total'] = 0;
				$vaultForTable['FDMS_case_num'] = $case_num;
				$vaultForTable['source'] = "Casket Showroom";
			}

			$results = $caseMerchandise->setCasketAndVaultForCase( $casketForTable, $vaultForTable, $case_num );

			$profile = array();
			$profile['casket'] = $casketForTable['item_description'];
			$profile['vault'] = $vaultForTable['item_description'];

			$cases = new FDMSCases();
			$results = $cases->updateCase( $profile, $case_num );
			#Zend_Debug::dump($results);
			$results = $cases->getCaseInfoForFDMSCaseNum( $case_num );
			#Zend_Debug::dump($results);

			if($results['status']=="SUCCEEDED")
			{
				$ns->caseInfo = $results['rows'][0];
				#	Zend_Debug::dump($results);
			}
			#exit(0);
			$profile = array();
			$profile['casket'] = $casketForTable['item_description'];
			$profile['vault'] = $vaultForTable['item_description'];
			$cases = new FDMSCases();
			$results = $cases->updateCase( $profile, $case_num );

			// redirect to next module in specified sequence

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->caskets = $caskets;
		$this->view->vaults = $vaults;

		$this->view->title = "Caskets";

		// need API call to get caskets and burial vaults

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page

		// record entry into module
		$ns->entryTime = time();
	}

	public function vascremationAction()
	{
		$req = $this->getRequest();
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$locale_id = $caseFHinfo['locale_id'];
		$branch_num = $caseFHinfo['branch_number'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "CREMATION";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		if(!$caseFHinfo['show_packages'])
		{
			// 1. can't show tributes, so we need to do the following:
			//    a. get next module action
			$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
			$nextModule = VASProcessModules::$_modules[$nextModuleKey];
			$nextModuleAction = $nextModule[1];
			//	  b. add it to session cache as "return_address"
			$ns->return_address = $nextModuleAction;
			//	  c. redirect to vasalacarteAction
			$this->_redirect('/index/vasalacarte');
		}

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$results = FDMSAPIcalls::getCremationTributesForLocaleId( $locale_id );
		$rows = $results['rows'];
		$tributes = array();
		foreach($rows as $row)
		$tributes[$row['package_id']] = $row['package_type'];

		$this->view->tributes = $tributes;

		//		$nextModuleKey = "URN";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// record $tribute
			$selected_tribute_id = $req->getParam('tribute');
			$selected_tribute_name = $tributes[$selected_tribute_id];

			$caseInfo['tribute_chosen'] = $selected_tribute_name;
			$ns->caseInfo = $caseInfo;

			$profile = array( 'tribute_chosen'=>$selected_tribute_name );
			$casesModel = new FDMSCases();
			$casesModel->updateCase( $profile, $case_num );

			$selected_tribute_v = "$selected_tribute_name";
			$cases = new FDMSCases();
			$cases->setTributeForCase( $selected_tribute_v, $case_num );

			$ns->caseInfo['tribute_selected'] = $selected_tribute_v;

			$results = FDMSAPIcalls::getPackageDetailsForPackageId( $selected_tribute_id, $locale_id );
			if($results['status'] != "SUCCEEDED")
			{
				// if we blew chow getting this, add a message and redisplay the page
			}

			// otherwise, capture items and dump them for the moment
			// look up items in package using FDMS API
			$details = $results['rows'];

			// sift through the $details and pick out the merchandise, services, and
			// cash advances so we can put them into the right cart table
			$cart_merchandise = array();
			$cart_services = array();
			$cart_cashadvances = array();

			foreach( $details as $pkg_item )
			{
				$pkg_item['source'] = $selected_tribute_name;
				$category = $pkg_item['item_category'];
				if($category == "SRV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_services[] = $pkg_item;
				}
				else
				if($category == "ADV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_cashadvances[] = $pkg_item;
				}
				else
				if($category == "OTR")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = 1.0*$pkg_item['item_amount'];
					$cart_merchandise[] = $pkg_item;

				}
			}

			$caseMerch = new CaseMerchandise();
			$results = $caseMerch->setItemsForCase( $cart_merchandise, $case_num );

			$caseServices = new CaseServices();

			$results = $caseServices->setItemsForCase( $cart_services, $case_num );

			$caseCashAdvances = new CaseCashAdvances();
			$results = $caseCashAdvances->setItemsForCase( $cart_cashadvances, $case_num );

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$tributesModel = new TributePackages();
		$bullet_points = array();
		foreach( $tributes as $id=>$type )
		{
			$bullet_points[$type] = array();
			$results = $tributesModel->getBulletPointsForTribute( $type );
			if($results['status']=="SUCCEEDED")
			{
				$bpXMLstr = $results['rows'][0]['bigxml'];
				$bpXML = simplexml_load_string( $bpXMLstr );
				foreach( $bpXML->bulletpoint as $bp )
				{
					$bullet_points[$type][] = "".$bp->name;
				}
			}
		}
		$this->view->bullet_points = $bullet_points;

		$this->view->title = "Cremation Tributes";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasnotesAction()
	{
		$this->_helper->layout()->disableLayout();
		$request = $this->getRequest();
		if($request->isGet())
		{
			$case_number = $request->getParam('case_number');
			$cases = new FDMSCases();
			$results = $cases->getCaseInfoForFDMSCaseNum( $case_number );

			if($results['status']=="SUCCEEDED")
			{
				$caseInfo = $results['rows'][0];
				$this->view->status = "OK";
				$this->view->case_number = $case_number;
				$this->view->notes = $caseInfo['general_note'];
			}
			else
			{
				$this->view->status = "NOT_OK";
				$this->view->message = "Unable to retrieve information for case";
			}
		}
		else
		if($request->isPost())
		{
			$case_number = $request->getParam('case_number');
			$cases = new FDMSCases();
			$notes = $request->getParam('notes');
			$profile = array('general_note'=>$notes);
			$results = $cases->updateCase( $profile, $case_number );
		}
	}

	public function vasurnAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$locale_id = $caseFHinfo['locale_id'];
		$branch_num = $caseFHinfo['branch_number'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "URN";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "SERVICES";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		// get list of urns from FDMS
		// get list of caskets and vaults from FDMS.  as a placeholder, put up two SELECT menus
		// - one for caskets, one for vaults - and pick from that.
		//$results = FDMSAPIcalls::getUrnsAndVaultsForBranchNumber( $branch_num );
		
		$InvoiceMaster = new InvoiceMaster();
		$results = $InvoiceMaster->SelectMerchandiseByFuneralHomeId( $branch_num );

		$urns = array();
		$vaults = array();

		foreach( $results as $inventory_item )
		{
			if(stripos($inventory_item['item_category'],"Urn Vault")!==false)
			{
				$vaults[$inventory_item['inventory_master_id']] = $inventory_item;
			}
			else
			if(stripos($inventory_item['item_category'],"Urn")!==false)
			{
				$urns[$inventory_item['inventory_master_id']] = $inventory_item;
			}
		}

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$urn_kmnumber = $req->getParam('urn_number');
			$vault_kmnumber = $req->getParam('vault_number');

			$urn_id = -1;
			foreach($urns as $uid=>$urn)
			{
				if(false != strpos($urn['item_description'], $urn_kmnumber))
				{
					$urn_id = $uid;
				}
			}

			$vault_id = -1;
			foreach($vaults as $vid=>$vault)
			{
				if(false != strpos($vault['item_description'], $vault_kmnumber))
				{
					$vault_id = $vid;
				}
			}

			// add chosen casket to case merchandise table
			$urnForTable = array();

			if($urn_id != -1)
			{
				$selectedUrn = $urns[$urn];

				$urnForTable['price_list_id'] = $selectedUrn['inventory_master_id'];
				$urnForTable['item_category'] = "Urn";
				//			$casketForTable['item_name'] = $selectedCasket['item_name'];
				$urnForTable['line_number'] = $selectedUrn['line_number'];
				$urnForTable['item_description'] = $selectedUrn['item_name'];
				$urnForTable['item_amount'] = $selectedUrn['item_amount'];
				$urnForTable['qty'] = 1;
				$urnForTable['total'] = $urnForTable['item_amount'];
				$urnForTable['FDMS_case_num'] = $case_num;
				$urnForTable['source'] = "Urn Showroom";
			}
			else
			{
				$urnForTable['price_list_id'] = -1;
				$urnForTable['item_category'] = "Urn";
				$urnForTable['line_number'] = -1;
				$urnForTable['item_description'] = "$urn_kmnumber - Description not available";
				$urnForTable['item_amount'] = -1;
				$urnForTable['qty'] = 0;
				$urnForTable['total'] = -1;
				$urnForTable['FDMS_case_num'] = $case_num;
				$urnForTable['source'] = "Urn Showroom";
			}

			// qty, total, FDMS_case_num, source

			// add chosen vault to case merchandise table
			$vaultForTable = array();

			if($vault_id != -1)
			{
				$selectedVault = $vaults[$vault];

				$vaultForTable['price_list_id'] = $selectedVault['inventory_master_id'];
				$vaultForTable['item_category'] = "Urn Vault";
				//		$vaultForTable['item_name'] = $selectedVault['item_name'];
				$vaultForTable['line_number'] = $selectedVault['line_number'];
				$vaultForTable['item_description'] = $selectedVault['item_name'];
				$vaultForTable['item_amount'] = $selectedVault['item_amount'];
				$vaultForTable['qty'] = 1;
				$vaultForTable['total'] = $vaultForTable['item_amount'];
				$vaultForTable['FDMS_case_num'] = $case_num;
				$vaultForTable['source'] = "Urn Showroom";
			}
			else
			{
				$vaultForTable['price_list_id'] = -1;
				$vaultForTable['item_category'] = "Urn Vault";
				//		$vaultForTable['item_name'] = $selectedVault['item_name'];
				$vaultForTable['line_number'] = -1;
				$vaultForTable['item_description'] = "$vault_kmnumber - Description not available";
				$vaultForTable['item_amount'] = -1;
				$vaultForTable['qty'] = 0;
				$vaultForTable['total'] = -1;
				$vaultForTable['FDMS_case_num'] = $case_num;
				$vaultForTable['source'] = "Urn Showroom";
			}

			$caseMerchandise = new CaseMerchandise();
			$results = $caseMerchandise->setUrnAndVaultForCase( $urnForTable, $vaultForTable, $case_num );

			$profile = array();
			$profile['urn'] = $urnForTable['item_description'];
			$profile['vault'] = $vaultForTable['item_description'];
			$cases = new FDMSCases();
			$results = $cases->updateCase( $profile, $case_num );

			$caseInfo['urn'] = $profile['urn'];
			$caseInfo['vault'] = $profile['vault'];

			$ns->caseInfo = $caseInfo;

			if($ns->cameFromAlaCarte == "Y")
			{
				$nextModuleAction = "vasservices";
				unset($ns->cameFromAlaCarte);
			}

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Urns";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		$this->view->urns = $urns;
		$this->view->vaults = $vaults;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasmemorialAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );
		$req = $this->getRequest();

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$locale_id = $caseFHinfo['locale_id'];

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$locale_id = $caseFHinfo['locale_id'];
		$branch_num = $caseFHinfo['branch_number'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "MEMORIAL";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "SERVICES";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$results = FDMSAPIcalls::getMemorialTributesForLocaleId( $locale_id );

		$rows = $results['rows'];
		$tributes = array();
		foreach($rows as $row)
		$tributes[$row['package_id']] = $row['package_type'];

		$this->view->tributes = $tributes;

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// record $tribute
			$selected_tribute_id = $req->getParam('tribute');
			$selected_tribute_name = $tributes[$selected_tribute_id];

			$caseInfo['tribute_chosen'] = $selected_tribute_name;
			$ns->caseInfo = $caseInfo;

			$profile = array( 'tribute_chosen'=>$selected_tribute_name );

			$casesModel = new FDMSCases();
			$casesModel->updateCase( $profile, $case_num );

			$results = FDMSAPIcalls::getPackageDetailsForPackageId( $selected_tribute_id, $locale_id );
			if($results['status'] != "SUCCEEDED")
			{
				// if we blew chow getting this, add a message and redisplay the page
			}

			// otherwise, capture items and dump them for the moment
			// look up items in package using FDMS API
			$details = $results['rows'];

			// sift through the $details and pick out the merchandise, services, and
			// cash advances so we can put them into the right cart table
			$cart_merchandise = array();
			$cart_services = array();
			$cart_cashadvances = array();

			foreach( $details as $pkg_item )
			{
				$pkg_item['source'] = $selected_tribute_name;
				$category = $pkg_item['item_category'];
				if($category == "SRV")
				{
					$cart_services[] = $pkg_item;
				}
				else
				if($category == "ADV")
				{
					$cart_cashadvances[] = $pkg_item;
				}
				else
				if($category == "OTR")
				{
					$cart_merchandise[] = $pkg_item;
				}
			}

			$caseMerch = new CaseMerchandise();
			$caseMerch->setItemsForCase( $cart_merchandise, $case_num );

			$caseServices = new CaseServices();
			$caseServices->setItemsForCase( $cart_services, $case_num );

			$caseCashAdvances = new CaseCashAdvances();
			$caseCashAdvances->setItemsForCase( $cart_cashadvances, $case_num );

			// redirect to next module in specified sequence

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$tributesModel = new TributePackages();
		$bullet_points = array();
		foreach( $tributes as $id=>$type )
		{
			$bullet_points[$type] = array();
			$results = $tributesModel->getBulletPointsForTribute( $type );
			if($results['status']=="SUCCEEDED")
			{
				$bpXMLstr = $results['rows'][0]['bigxml'];
				$bpXML = simplexml_load_string( $bpXMLstr );
				foreach( $bpXML->bulletpoint as $bp )
				{
					$bullet_points[$type][] = "".$bp->name;
				}
			}
		}
		$this->view->bullet_points = $bullet_points;

		$this->view->title = "Memorial Tributes";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasalacarteAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$req = $this->getRequest();

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$locale_id = $caseFHinfo['locale_id'];
		$branch_num = $caseFHinfo['branch_number'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "ALACARTE";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		// get non-tribute packages from FDMS
		// get the available FDMS burial tributes for this locale
		//		$results = FDMSAPIcalls::getOtherOfferingsForLocaleId( $locale_id );

		$PriceListObj = new PriceList();
		$rows = $PriceListObj->getOtherOfferingsForLocaleId($locale_id);

		$packages = array();
		foreach($rows as $row)
		{
			$add = false;
			if( $caseInfo['choice'] == "BURIAL" )
			{
				if(strpos( $row['package_type'], "Burial" )) $add = true;
			}
			else
			if( $caseInfo['choice'] == "CREMATION" )
			{
				if(strpos( $row['package_type'], "Cremation" )) $add = true;
			}

			if($add)
			$packages[$row['package_id']] = $row['package_type'];
		}

		$this->view->packages = $packages;

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$selected_package_id = $req->getParam('package');
			$selected_package_name = $packages[$selected_package_id];

			$caseInfo['tribute_chosen'] = $selected_package_name;

			$ns->caseInfo = $caseInfo;

			//			$results = FDMSAPIcalls::getPackageDetailsForPackageId( $selected_package_id, $locale_id );
			$details = $PriceListObj->getPackageDetailsForPackageId( $selected_package_id, $locale_id );

			// sift through the $details and pick out the merchandise, services, and
			// cash advances so we can put them into the right cart table
			$cart_merchandise = array();
			$cart_services = array();
			$cart_cashadvances = array();

			foreach( $details as $pkg_item )
			{
				$pkg_item['source'] = $selected_package_name;
				$category = $pkg_item['item_category'];
				if($category == "SRV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_services[] = $pkg_item;
				}
				else
				if($category == "ADV")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_cashadvances[] = $pkg_item;
				}
				else
				if($category == "OTR")
				{
					$pkg_item['qty'] = 1.0;
					$pkg_item['total'] = $pkg_item['item_amount'];
					$cart_merchandise[] = $pkg_item;
				}
			}

			$caseMerch = new CaseMerchandise();
			$caseMerch->setItemsForCase( $cart_merchandise, $case_num );

			//			echo "Merchandise in cart:<br>";
			//			$merch2 = $caseMerch->getItemsForCase( $case_num );
			//			Zend_Debug::dump($merch2);

			//			echo "setting services into shopping cart...<br>";
			$caseServices = new CaseServices();
			$caseServices->setItemsForCase( $cart_services, $case_num );

			//			echo "Services in cart:<br>";
			//			$srv2 = $caseServices->getItemsForCase( $case_num );
			//			Zend_Debug::dump($srv2);

			$caseCashAdvances = new CaseCashAdvances();
			$caseCashAdvances->setItemsForCase( $cart_cashadvances, $case_num );

			// redirect to next module in specified sequence
			if(isset($ns->return_address))
			{
				$return_address = $ns->return_address;
				unset($ns->return_address);
				$this->_redirect('/index/'.$return_address);
			}

			# if we're here, we got here because we skipped the
			# tribute page.  so, depending on whether we're burial
			# or cremation we need to set $nextModuleAction
			# to vascasket or vasurn, and add a $cameFromAlacarte var
			# to the session cache so we know to go to vasservices
			# (and to delete said flag when we do) from the respective
			# showroom.

			if( $caseInfo['choice'] == "BURIAL" )
			{
				$nextModuleAction = "vascasket";
				$ns->cameFromAlaCarte = "Y";
			}
			else
			if($caseInfo['choice'] == "CREMATION" )
			{
				$nextModuleAction = "vasurn";
				$ns->cameFromAlaCarte = "Y";
			}

			$cases = new FDMSCases();
			$cases->setTributeForCase( $selected_package_name, $case_num );

			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Other Offerings";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasservicesAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "SERVICES";
		$this->view->currentVASpage = "SERVICES";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		// redirect to next module in specified sequence
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		// get services for this locale id
//		$results = FDMSAPIcalls::getServicesForLocaleId( $locale_id );
		// get services already in cart
		$caseServices = new CaseServices();
		
		$catalog = $caseServices->getServicesForLocaleId($locale_id);
		$this->view->catalog = $catalog;

		$cart_services = $caseServices->getItemsForCase( $case_num );
		$this->view->cart = $cart_services;

		$req = $this->getRequest();
		$ns->return_page = $req->getParam('return_page');
		$ns->save_breadcrumbs = $ns->breadcrumbs;

		$ns->save_breadcrumbs = $ns->breadcrumbs;
		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$itemsXMLstr = $req->getParam('cartItems');
			$itemsXML = simplexml_load_string( $itemsXMLstr );

			$cartItems = array();
			// now unpack $itemsXML and set it to be the cart_services for this case
			foreach( $itemsXML->cartItem as $item )
			{
				$cartItem = array();

				$cartItem['source'] = "".$item->type;
				$cartItem['item_category'] = "".$item->category;
				$cartItem['price_list_id'] = "".$item->price_list_id;
				$cartItem['item_description'] = "".$item->name;
				$cartItem['item_amount'] = "".$item->price;
				$cartItem['line_number'] = "".$item->CL;

				$cartItem['qty'] = "".$item->qty;
				$cartItem['total'] = "".$item->total;

				$cartItems[] = $cartItem;
			}

			$results = $caseServices->setItemsForCase( $cartItems, $case_num );

			// redirect to next module in specified sequence
			$return_page = $ns->return_page;
			unset($ns->return_page);
			if(isset($return_page))
			{
				$ns->breadcrumbs = $ns->save_breadcrumbs;
				unset($ns->save_breadcrumbs);
				$this->_redirect('/index/'.$return_page);
			}
			else
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->hide_breadcrumbs = false;
		$this->view->change_next_button = false;
		$this->view->hide_back_button = false;
		if(isset($ns->return_page))
		{
			$this->view->hide_breadcrumbs = true;
			$this->view->change_next_button = true;
			$this->view->hide_back_button = true;
		}

		$this->view->title = "Services";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasstepsummaryAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');


		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];

		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "STEPSUMMARY";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		// redirect to next module in specified sequence
		//		$nextModuleKey = "CATERING";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Service Summary";

		// what goes into step summary?

		// BURIAL/CREMATION					(add to case record)
		// Tribute selected (or a la carte) (add to case record)
		// Casket/Vault or Urn/Vault		(get from CaseMerchandise)
		// list of services					(get from CaseServices)

		$caseMerch = new CaseMerchandise();
		$caseServices = new CaseServices();

		// to get casket and vault, first get list of merch for case
		$merch = $caseMerch->getItemsForCase( $case_num );

		# replace this with stuff from case record
		$selections = array();

		if($caseInfo['choice'] == "BURIAL") {
			$selections[] = array( "item_description"=>"Casket: ".$caseInfo['casket'] );
			$selections[] = array( "item_description"=>"Vault: ".$caseInfo['vault'] );
		}
		else
		if($caseInfo['choice'] == "CREMATION") {
			$selections[] = array( "item_description"=>"Urn: ".$caseInfo['urn'] );
			$selections[] = array( "item_description"=>"Cremation Casket: ".$caseInfo['vault'] );
		}
		/*
		// then filter in Casket and Vault category
		foreach( $merch as $merch_item )
		{
		if($caseInfo['choice']=="BURIAL")
		{
		if($merch_item['item_category'] == "Casket")
		{
		$selections[] = $merch_item;
		}
		else
		if($merch_item['item_category'] == "Vault")
		{
		$selections[] = $merch_item;
		}
		}
		else
		if($caseInfo['choice']=="CREMATION")
		{
		if($merch_item['item_category'] == "Urn")
		{
		$selections[] = $merch_item;
		}
		else
		if($merch_item['item_category'] == "Urn Vault")
		{
		$selections[] = $merch_item;
		}
		}
		}
		*/

		// just get the list of services straight from the caseservices record
		$results = $caseServices->getItemsForCase( $case_num );
		$services = $results;

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;

		$this->view->choice = $ns->caseInfo['choice'];
		$this->view->tribute = $ns->caseInfo['tribute_selected'];
		$this->view->services = $services;

		$this->view->selections = $selections;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// get ready to display module page

		// record entry into module
		$ns->entryTime = time();
	}

	public function vascateringAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$casesModel = new FDMSCases();

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$req = $this->getRequest();
		$ns->return_page = $req->getParam('return_page');
		$ns->save_breadcrumbs = $ns->breadcrumbs;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "CATERING";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$this->view->branch_id = $caseInfo['branch_id'];
		$this->view->branch_number = $caseInfo['branch_num'];

		$moduleTimes = new VASModuleTimes();

		// redirect to next module in specified sequence
		//		$nextModuleKey = "FLORAL";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// record catering info from module
			$location = $req->getParam('location');		// -> $row['location']

			$datetime = $req->getParam('datetime');

			$caterer = $req->getParam('caterer');		// -> $row['caterer']
			$menu = $req->getParam('menu');				// -> $row['menu']
			$headcount = $req->getParam('headcount');	// -> $row['headcount']
			$total_cost = $req->getParam('total');		// -> $row['catering_total']
			$notes = $req->getParam('notes');			// -> $row['catering_notes']

			// write these into the case record
			$profile = array();
			$profile['location'] = addslashes(stripslashes($location));
			$profile['datetime'] = addslashes(stripslashes($datetime));
			$profile['caterer'] = addslashes(stripslashes($caterer));
			$profile['menu'] = addslashes(stripslashes($menu));
			$profile['headcount'] = addslashes(stripslashes($headcount));
			$profile['catering_total'] = addslashes(stripslashes($total_cost));
			$profile['catering_notes'] = addslashes(stripslashes($notes));
			$case_num = addslashes(stripslashes($case_num));

			$results = $casesModel->updateCase( $profile, $case_num );
			$caseInfo = $ns->caseInfo;
			$caseInfo['location'] = addslashes(stripslashes($location));
			$caseInfo['datetime'] = addslashes(stripslashes($datetime));
			$caseInfo['caterer'] = addslashes(stripslashes($caterer));
			$caseInfo['menu'] = addslashes(stripslashes($menu));
			$caseInfo['headcount'] = addslashes(stripslashes($headcount));
			$caseInfo['catering_total'] = addslashes(stripslashes($total_cost));
			$caseInfo['catering_notes'] = addslashes(stripslashes($notes));
			$ns->caseInfo = $caseInfo;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			# try to dig return page from session cache, then erase it.
			$return_page = $ns->return_page;
			unset($ns->return_page);
			if(isset($return_page))
			{
				$ns->breadcrumbs = $ns->save_breadcrumbs;
				unset($ns->save_breadcrumbs);
				$this->_redirect('/index/'.$return_page);
			}
			else
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->hide_breadcrumbs = false;
		$this->view->change_next_button = false;
		$this->view->hide_back_button = false;
		if(isset($ns->return_page))
		{
			$this->view->hide_breadcrumbs = true;
			$this->view->change_next_button = true;
			$this->view->hide_back_button = true;
		}

		$this->view->title = "Catering / Reception";
		$this->view->currentVASpage = "CATERING";
		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $caseFDinfo;
		$this->view->caseFHinfo = $caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasfloralAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$casesModel = new FDMSCases();

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$req = $this->getRequest();

		# location of page to return to if we're from vasfullsummary.  put in session
		# cache until POST
		$ns->return_page = $req->getParam('return_page');
		$ns->save_breadcrumbs = $ns->breadcrumbs;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "FLORAL";
		$this->view->currentVASpage = "FLORAL";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$moduleTimes = new VASModuleTimes();

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			$adjustment = $req->getParam('adjustment');

			$florist = addslashes(stripslashes($req->getParam('florist')));
			$collectionsXML = addslashes(stripslashes($req->getParam('collections')));
			$total = addslashes(stripslashes($req->getParam('total')));
			$total = str_replace(",", "", $total);
			$total = str_replace("\$", "", $total);
			$notes = addslashes(stripslashes($req->getParam('notes')));
			$adjustment = addslashes(stripslashes($req->getParam('adjustment')));

			// write them into the case record
			$profile = array();

			$profile['florist'] = $florist;
			$profile['arrangement'] = $collectionsXML;
			$profile['floral_total'] = $total;
			$profile['floral_notes'] = $notes;
			$profile['adjustment'] = $adjustment;

			$results = $casesModel->updateCase( $profile, $case_num );

			$caseInfo = $ns->caseInfo;
			$caseInfo['florist'] = $florist;
			$caseInfo['arrangement'] = $collectionsXML;
			$caseInfo['floral_total'] = $total;
			$caseInfo['floral_notes'] = $notes;
			$caseInfo['adjustment'] = $adjustment;
			$ns->caseInfo = $caseInfo;

			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
			$nextModule = VASProcessModules::$_modules[$nextModuleKey];
			$nextModuleAction = $nextModule[1];

			# try to dig return page from session cache, then erase it.
			$return_page = $ns->return_page;
			unset($ns->return_page);

			# if there was a return page in the session cache, go to it.  otherwise,
			# just go to the next page in sequence
			if(isset($return_page))
			{
				$ns->breadcrumbs = $ns->save_breadcrumbs;
				unset($ns->save_breadcrumbs);
				$this->_redirect('/index/'.$return_page);
			}
			else
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->hide_breadcrumbs = false;
		$this->view->change_next_button = false;
		$this->view->hide_back_button = false;
		if(isset($ns->return_page))
		{
			$this->view->hide_breadcrumbs = true;
			$this->view->change_next_button = true;
			$this->view->hide_back_button = true;
		}

		$this->view->title = "Floral Selections";

		$this->view->branch_id = $caseInfo['branch_id'];
		$this->view->branch_number = $caseInfo['branch_num'];

		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $caseFDinfo;
		$this->view->caseFHinfo = $caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	// this one is "merchandise" and its view script will have all the Dojo grid code in it.
	public function vasmementosAction()
	{
		$req = $this->getRequest();
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$FDMS_case_num = $caseInfo['FDMS_case_num'];
		$case_num = $caseInfo['FDMS_case_num'];
		$branch_number = $caseFHinfo['branch_num'];
		$localeId = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];
		$this->view->locale_id = $localeId;

		$ns->return_page = $req->getParam('return_page');
		$ns->save_breadcrumbs = $ns->breadcrumbs;

		// merchandise they've already bought (cart)
		$caseMerch = new CaseMerchandise();
		$items = $caseMerch->getItemsForCase( $case_num );

		$this->view->cart = $caseMerch->getItemsForCase( $case_num );

		// merchandise they can buy (catalog)
		$results = FDMSAPIcalls::getMerchandiseForLocaleId( $localeId );
		$rawmerch = $results['rows'];
		$merchandise = array();
		foreach( $rawmerch as $merch_item )
		{
			if($merch_item['item_category']=='SRV' ||
			$merch_item['item_category']=='ADV' ||
			$merch_item['item_category']=='DIS') continue;
			$merchandise[] = $merch_item;
		}

		$this->view->catalog = $merchandise;

		$ns->currentModuleKey = "MERCHANDISE";
		$this->view->currentVASpage = "MERCHANDISE";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		//		$nextModuleKey = "CASHADV";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$caseMerchandise = new CaseMerchandise();
		$cart_merchandise = $caseMerchandise->getItemsForCase( $case_num );
		$this->cart = $cart_merchandise;

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		if($req->isPost())
		{
			// record merchandise info from page
			$p = $req->getParams();

			$cartItemsStr = $p['cartItems'];
			$cartItemsXML = simplexml_load_string($cartItemsStr);
			$cartItemsToInsert = array();
			foreach($cartItemsXML as $cartItem)
			{
				$item = array();
				$item['price_list_id'] = "".$cartItem->price_list_id;
				$item['item_category'] = "".$cartItem->category;
				$item['item_description'] = "".$cartItem->name;
				$item['line_number'] = "".$cartItem->CL;
				$item['item_amount'] = "".$cartItem->price;
				$item['qty'] = "".$cartItem->qty;
				$item['total'] = "".$item['item_amount'] * $item['qty'];
				$item['source'] = "".$cartItem->type;
				$cartItemsToInsert[] = $item;
			}

			$caseMerchandise->setItemsForCase( $cartItemsToInsert, $case_num );

			$paper_options = trim($p['paper_stock']);
			list($category, $verse) = explode( ' / ', $paper_options);

			$profile = array();
			$profile['paper_stock_category'] = $category;
			$profile['verse'] = $verse;
			$caseModel = new FDMSCases();
			$results = $caseModel->updateCase( $profile, $case_num );
			$caseInfo = $ns->caseInfo;
			$caseInfo['paper_stock_category'] = $category;
			$caseInfo['verse'] = $verse;
			$ns->caseInfo = $caseInfo;

			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $localeId, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;
			// go to next page in sequence
			// redirect to next module in specified sequence
			$return_page = $ns->return_page;
			unset($ns->return_page);
			if(isset($return_page))
			{
				$ns->breadcrumbs = $ns->save_breadcrumbs;
				unset($ns->save_breadcrumbs);
				$this->_redirect('/index/'.$return_page);
			}
			else
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->hide_breadcrumbs = false;
		$this->view->change_next_button = false;
		$this->view->hide_back_button = false;
		if(isset($ns->return_page))
		{
			$this->view->hide_breadcrumbs = true;
			$this->view->change_next_button = true;
			$this->view->hide_back_button = true;
		}

		$this->view->title = "Merchandise";
		$this->locale_id = $localeId;
		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vascashadvancesAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		// "family reminders" in cash advance page. bleah.
		$things_to_bring = $caseInfo['things_to_bring'];

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "CASHADV";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		//		$nextModuleKey = "FULLSUMMARY";
		$moduleTimes = new VASModuleTimes();

		// redirect to next module in specified sequence
		//		$nextModuleKey = "FULLSUMMARY";
		//		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		//		$nextModuleAction = $nextModule[1];

		$results = FDMSAPIcalls::getCashAdvancesForLocaleId($locale_id);
		$locale_cash_advances = $results['rows'];
		$count = count($locale_cash_advances);
		for( $i=0; $i<$count; $i++ )
		{
			$locale_cash_advances[$i]['id'] = $i;
		}

		//exit(0);
		$caseCashAdv = new CaseCashAdvances();
		$case_cash_advances = $caseCashAdv->getItemsForCase( $case_num );

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		$ns->return_page = $req->getParam('return_page');
		$ns->save_breadcrumbs = $ns->breadcrumbs;

		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// record cash advances to shopping cart
			$p = $req->getParams();

			$things_to_bring = $p['things_to_bring'];
			$profile = array('things_to_bring'=>$things_to_bring);
			$caseModel = new FDMSCases();
			$caseModel->updateCase( $profile, $case_num );

			$ns->caseInfo['things_to_bring'] = $things_to_bring;

			$cartItemsStr = $p['cartItems'];
			$cartItemsXML = simplexml_load_string($cartItemsStr);

			$cartItems = array();
			foreach( $cartItemsXML->cartItem as $item )
			{
				$cartItem = array();

				$cartItem['source'] = "".$item->type;
				$cartItem['item_category'] = "".$item->category;
				$cartItem['price_list_id'] = "".$item->price_list_id;
				$cartItem['item_description'] = "".$item->name;
				$cartItem['item_amount'] = "".$item->price;
				$cartItem['line_number'] = "".$item->CL;
				$cartItem['qty'] = "".$item->qty;
				$cartItem['total'] = "".$item->total;

				$cartItems[] = $cartItem;
			}

			$results = $caseCashAdv->setItemsForCase( $cartItems, $case_num );

			$errorStr = $caseCashAdv->getErrorStr();
			$errorCode = $caseCashAdv->getErrorCode();

			$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
			$nextModule = VASProcessModules::$_modules[$nextModuleKey];
			$nextModuleAction = $nextModule[1];

			// redirect to next module in specified sequence
			$return_page = $ns->return_page;
			unset($ns->return_page);
			if(isset($return_page))
			{
				$ns->breadcrumbs = $ns->save_breadcrumbs;
				unset($ns->save_breadcrumbs);
				$this->_redirect('/index/'.$return_page);
			}
			else
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->hide_breadcrumbs = false;
		$this->view->change_next_button = false;
		$this->view->hide_back_button = false;
		if(isset($ns->return_page))
		{
			$this->view->hide_breadcrumbs = true;
			$this->view->change_next_button = true;
			$this->view->hide_back_button = true;
		}

		$this->view->title = "Cash Advances";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->currentVASpage = "CASHADV";
		$this->view->catalog = $locale_cash_advances;
		$this->view->cart = $case_cash_advances;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasfullsummaryAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$case_num = $ns->caseInfo['FDMS_case_num'];

		$modules = $ns->modules;
		//		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;


		// need to refresh $ns->caseInfo from the db
		$caseModel = new FDMSCases();
		$fhModel = new FuneralHomes();
		$usersModel = new Users();

		$results = $caseModel->getCaseInfoForFDMSCaseNum( $case_num );
		if($results['status'] == "SUCCEEDED")
		{
			$caseInfo = $results['rows'][0];
		}

		$ns->caseInfo = $caseInfo;
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "FULLSUMMARY";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		//		$nextModuleKey = "VITALS";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Full Summary";

		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $caseFDinfo;
		$this->view->caseFHinfo = $caseFHinfo;

		// don't forget services, cash advances, merchandise, catering, and floral
		$caseServices = new CaseServices();
		$caseCashAdvances = new CaseCashAdvances();
		$caseMerchandise = new CaseMerchandise();

		$caseMerchItems = $caseMerchandise->getItemsForCase( $case_num );
		$selections = array();
		$merchItems = array();
		// then filter in Casket and Vault category
		foreach( $caseMerchItems as $merch_item )
		{
			if($caseInfo['choice']=="BURIAL")
			{
				if($merch_item['item_category'] == "Casket")
				{
					$selections["Casket"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
			else
			if($caseInfo['choice']=="CREMATION")
			{
				if($merch_item['item_category'] == "Urn")
				{
					$selections["Urn"] = $merch_item;
				}
				else
				if($merch_item['item_category'] == "Urn Vault")
				{
					$selections["Vault"] = $merch_item;
				}
				else
				$merchItems[] = $merch_item;
			}
		}


		$this->view->caseMerchItems = $merchItems;
		$this->view->selections = $selections;
		$this->view->caseServicesItems = $caseServices->getItemsForCase( $case_num );
		$this->view->caseCashAdvanceItems = $caseCashAdvances->getItemsForCase( $case_num );

		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	// big kahuna
	public function vasvitalsAction()
	{
		//		require_once("FDMSsandbox.php");
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		require_once('FDMSsandbox.php');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$vitals_id = $caseInfo['FDMS_vitals_id'];
		$username = $ns->user_profile['username'];
		$password = $ns->user_profile['password'];

		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "VITALS";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		// actually, replace the action script with /keystone/index/vasvitals
		// and capture the $_POST vars, then pass them into update_FDMS_vitals() along with
		// the jssession id.

		$req = $this->getRequest();
		if($req->isPost())
		{
			$p = $req->getParams();

			$jsessionid = $ns->jsessionid;
			$result = update_FDMS_vitalsPage( $jsessionid, $p );

			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$head_links = null;
		$head_script = null;
		$results = keystone_FDMS_login( $username, $password );
		$jsessionid = $results['jsessionid'];

		if(0)
		{
			$results = keystone_FDMS_login( $username, $password );

			$jsessionid = $results['jsessionid'];
			if($results['status'] == "Not logged in")
			{
				$body_contents = "<h1>Unable to access FDMS Vital Statistics page.  Your VAS username and password do not match your FDMS username and password.  Please contact your administrator.</h1>";
			}
			else
			{
				// $fucking_vitals_url = "\"http://keystone.aldorsolutions.com/webfdms/showVitals.do?vitalsId=$vitals_id&JSSESSIONID=$jsessionid\"";
				//$body_contents .= "<a href='#' onclick='javascript:window.open($fucking_vitals_url, \"_blank\", \"toolbar=no,location=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,left=10,top=10,width=800,height=800\")'>Click here to open FDMS</a> ";
				// $body_contents = "<a href=$fucking_vitals_url>Click here</a>";

				$results = fetch_FDMS_vitalsPage( $vitals_id, $jsessionid );
				if($results['in_vitals_page'] == "yes")
				{
					setcookie("JSESSIONID", $jsessionid);
					$ns->jsessionid = $jsessionid;
					$head_links = $results['head_links'];
					$head_scripts = $results['head_scripts'];
					$body_contents = $results['page_body'];
				}
				else
				{
					$body_contents = "<h1>Unable to access FDMS Vital Statistics page.  Your VAS username and password do not match your FDMS username and password.  Please contact your administrator.</h1>";
				}

			}
		}
		else
		{
			// replace this with iframe reference

			/*
			<iframe src ="/default.asp" width="100%" height="300">
			<p>Your browser does not support iframes.</p>
			</iframe>
			*/
			//				$body_contents = "<b>Vitals Page Goes Here When Finished";
			//$body_contents = "<iframe src=\"http://keystone.aldorsolutions.com/webfdms/showVitals.do?vitalsId=$vitals_id\" width=100% height=700>";
			//$body_contents .= "<p>Your browser does not support iframes.</br>";
			//$body_contents .= "</iframe>";
			$body_contents .= "<a href=\"http://keystone.aldorsolutions.com/webfdms/showVitals.do?vitalsId=$vitals_id\" target=\"_blank\">Click here to launch FDMS</a>	";
		}

		$this->view->currentVASpage = "VITALS";
		$this->view->title = "Vital Information";
		$this->view->vitals_form_html = $body_contents;
		$this->view->moduleAction = "/index/vasvitals";
		$this->view->head_links = $head_links;
		$this->view->head_scripts = $head_scripts;
		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasfirstcontactAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$casesModel = new FDMSCases();

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$name = $caseFHinfo['name'];
		$addr = $caseFHinfo['addr1'];
		$city = $caseFHinfo['city'];
		$state = $caseFHinfo['state'];
		$zip = $caseFHinfo['zip'];
		$phone = $caseFHinfo['phone'];

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$default_service_loc = "$name\n$addr\n$city, $state $zip\n$phone";
		if(!isset($caseInfo['service_loc']) || empty($caseInfo['service_loc']))
		{
			$caseInfo['service_loc'] = $default_service_loc;
		}

		$ns->currentModuleKey = "FIRSTCONTACT";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );
		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// get fields and update case record with them

			$profile = array();
			$posted = $req->getParams();

			$service_datetime = $posted['service_datetime'];
			$visit_datetime = $posted['visitation_datetime'];

			$service_date = substr( $service_datetime, 0, 10 );
			$service_time = substr( $service_datetime, 11 );

			$visit_date = substr( $visit_datetime, 0, 10 );
			$visit_time = substr( $visit_datetime, 11 );

			$profile['visitation_date'] = $visit_date;
			$profile['visitation_time'] = $visit_time;
			$profile['service_date'] = $service_date;
			$profile['service_time'] = $service_time;
			$profile['service_loc'] = $posted['service_loc'];
			$profile['contact_name'] = $posted['contact_name'];
			$profile['contact_address'] = $posted['contact_address'];
			$profile['contact_city'] = $posted['contact_city'];
			$profile['contact_state'] = $posted['contact_state'];
			$profile['contact_zip'] = $posted['contact_zip'];
			$profile['contact_phone'] = $posted['contact_phone'];
			$profile['contact_email'] = $posted['contact_email'];
			$profile['secondary_contact_name'] = $posted['secondary_contact_name'];
			$profile['secondary_contact_address'] = $posted['secondary_contact_address'];
			$profile['secondary_contact_city'] = $posted['secondary_contact_city'];
			$profile['secondary_contact_state'] = $posted['secondary_contact_state'];
			$profile['secondary_contact_zip'] = $posted['secondary_contact_zip'];
			$profile['secondary_contact_phone'] = $posted['secondary_contact_phone'];
			$profile['secondary_contact_email'] = $posted['secondary_contact_email'];

			$profile['family_advisor_name'] = $posted['family_advisor_name'];
			$profile['family_advisor_phone'] = $posted['family_advisor_phone'];
			$profile['family_advisor_cell_phone'] = $posted['family_advisor_cell_phone'];

			// add the rest of the first contact fields here
			$profile['cemetery_name'] = $posted['cemetery_name'];
			$profile['cemetery_address'] = $posted['cemetery_address'];
			$profile['cemetery_city'] = $posted['cemetery_city'];
			$profile['cemetery_state'] = $posted['cemetery_state'];
			$profile['cemetery_zip'] = $posted['cemetery_zip'];
			$profile['cemetery_phone'] = $posted['cemetery_phone'];
			$profile['cemetery_contact_name'] = $posted['cemetery_contact_name'];

			// safety-ify the profile
			foreach( $profile as $key=>$value )
			{
				if(null == $value) $profile[$key] = "";
				else $profile[$key] = addslashes($value);
			}


			// now udpate the case
			$results = $casesModel->updateCase( $profile, $case_num );
			// now retrieve it and add it to the session cache.
			$results = $casesModel->getCaseInfoForFDMSCaseNum( $case_num );
			if($results['status'] == "SUCCEEDED" )
			{
				$caseInfo = $results['rows'][0];
				//				Zend_Debug::dump($caseInfo);
				$ns->caseInfo = $caseInfo;
			}

			// redirect to next module in specified sequence
			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "First Contact";

		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasfinancialsAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "FINANCIALS";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		//		$nextModuleKey = "CLOSING";
		$nextModuleKey = $this->nextModule( $ns->modules, $ns->currentModuleKey );

		$nextModule = VASProcessModules::$_modules[$nextModuleKey];
		$nextModuleAction = $nextModule[1];

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			// vars - funding_options and paid_in_full
			$p = $req->getParams();
			$options = $req->getParam('funding_options');
			$paid_in_full = $req->getParam('paid_in_full');
			if($paid_in_full == 'on') $pif = 1;
			else $pif = 0;

			$caseModel = new FDMSCases();
			$results = $caseModel->setFinancialForCase($options, $paid_in_full, $case_num);
			// redirect to next module in specified sequence

			$caseInfo['funding_option'] = $options;
			$caseInfo['paid_in_full'] = $pif;
			$ns->caseInfo = $caseInfo;

			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;


			$this->_redirect( '/index/'.$nextModuleAction );
		}

		$this->view->title = "Your Financial Choices";

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasclosingAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;

		$case_num = $caseInfo['FDMS_case_num'];
		$branch_num = $caseFHinfo['branch_number'];
		$locale_id = $caseFHinfo['locale_id'];
		$FD_license_number = $ns->user_profile['FDMS_license_number'];

		$ns->currentModuleKey = "CLOSING";
		$caseInfo["current_module"] = $ns->currentModuleKey;

		$moduleTimes = new VASModuleTimes();

		$curModule = VASProcessModules::$_modules[$ns->currentModuleKey];
		$curModuleAction = $curModule[1];
		$actionURL = $this->view->url(array('controller'=>'index','action'=>$curModuleAction));

		$breadcrumbs = $this->breadcrumb_pop_prior( $ns->breadcrumbs, $ns->currentModuleKey );

		$req = $this->getRequest();
		if($req->isPost())
		{
			$exitTime = time();
			$timeInModule = $exitTime - $ns->entryTime;
			$moduleTimes->recordModuleTime( $ns->currentModuleKey, $case_num, $branch_num, $locale_id, $FD_license_number, $timeInModule );
			unset($ns->entryTime);

			$breadcrumbs = $this->breadcrumb_push( $breadcrumbs, $ns->currentModuleKey );
			$ns->breadcrumbs = $breadcrumbs;

			// set case status to 'FINISHED'
			$casesModel = new FDMSCases();
			$results = $casesModel->setStatusForCase( "FINISHED", $case_num );

			// redirect back to FD dashboard
			$this->_redirect( '/index/vasthankyou' );
		}

		$this->view->title = "Closing";

		//#1 - get cash advances for this case
		$caseCashAdvModel = new CaseCashAdvances();

		$this->view->cash_advance_items = $caseCashAdvModel->getItemsForCase( $case_num );

		$this->view->caseInfo = $ns->caseInfo;
		$this->view->caseFDinfo = $ns->caseFDinfo;
		$this->view->caseFHinfo = $ns->caseFHinfo;
		$this->view->breadcrumbs = $breadcrumbs;
		$this->view->arranger = $caseFDinfo;
		$this->view->currentVASpage = $ns->currentModuleKey;

		// record entry into module
		$ns->entryTime = time();
	}

	public function vasthankyouAction()
	{
		$this->_helper->layout->setLayout('VAS_modules');
		$ns = new Zend_Session_Namespace( "VAS" );

		if(!isset($ns->user_profile)) $this->_redirect('/index/login');
		if($ns->user_profile['role_name'] != "FD" &&
		$ns->user_profile['role_name'] != "FD_Admin")
		$this->_redirect('/index/login');

		$modules = $ns->modules;
		$caseInfo = $ns->caseInfo;
		$caseFDinfo = $ns->caseFDinfo;
		$caseFHinfo = $ns->caseFHinfo;
		$this->view->caseInfo = $caseInfo;
		$this->view->caseFDinfo = $caseFDinfo;
		$this->view->caseFHinfo = $caseFHinfo;
		$this->view->currentVASpage = "THANKYOU";
		if($this->getRequest()->isPost()) {
			$this->_redirect('/index/fddashboard');
		}
	}

	/////////////////////////////////////////////////////////////////////////////////////////////
	// XML methods to handle Brinton's Flash modules
	/////////////////////////////////////////////////////////////////////////////////////////////

	/////////////////////////////////////////////////////////////////////////////////////////////
	// JSON methods to vend data to the Dojo grids in the dashboard and merchandise pages
	/////////////////////////////////////////////////////////////////////////////////////////////

	public function ksfuneralhomesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;
		$this->_ks_id = $ns->ks_id;

		$ks_id = $ns->ks_id;

		// get list of funeral homes this admin can access.  this one will
		// *definitely* have to be scoped.
		$funeralHomes = new FuneralHomes();
		$results = $funeralHomes->getFuneralHomes();
		$funeral_homes = $results['rows'];

		$grid_homes = array();
		foreach( $funeral_homes as $home )
		{
			if(!empty($home['branch_id']))
			{
				//NOTE - funeral_home_id is a VAS id
				$grid_homes[] = array(
				"funeral_home_id" => $home['id'],
				"branch_id" => $home['branch_id'],
				"branch_number" => $home['branch_number'],
				"name" => $home['name'],
				"address" => $home['addr1'],
				"citystate" => $home['city'].", ".$home['state']
				);
			}
		}

		$resultsArray = array();
		$resultsArray['identifier'] = 'branch_number';
		$resultsArray['items'] = $grid_homes;
		echo json_encode($resultsArray);
	}

	public function ksfuneraldirectorsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_ks_id = $ns->ks_id;

		$ks_id = $ns->ks_id;

		// get funeral home id they want to get directors for
		$req = $this->getRequest();

		$users = new Users();

		$branch_number = $req->getParam("branch_number");

		$results = $users->fetchFuneralDirectorsForBranch( $branch_number );

		$resultsArray = array();
		$resultsArray['identifier'] = 'id';
		$funeral_directors = $results['rows'];

		$grid_dirs = array();
		foreach( $funeral_directors as $director )
		{
			$director_id = $director['FDMS_license_number'];

			// because of the ##$@! stupid way FDMS stores these things
			// I have to look in the $director['branchnums'] array
			// to find the index I use to look up the FD id so I can
			// assign it to $arranger_id.  yeesh!

			//$arranger_id = $director['id'];

			$branchnums = explode( ",", $director['branchnums']);
			$idx = array_search( $branch_number, $branchnums );

			if(false === $idx)
			continue;

			$arrangerids = explode( ",", $director['FD_ids'] );
			$arranger_id = $arrangerids[$idx];
			$username = $director['username'];

			//$director_name = $director['lname'] . ", " . $director['fname'];
			$director_name = $director['full_name'];
			$grid_dirs[] = array(
			"id"=>$director_id,
			"arranger_id"=>$arranger_id,
			"name" => $director_name,
			"username" => $username
			);
		}

		$resultsArray['items'] = $grid_dirs;
		echo json_encode($resultsArray);
	}

	public function kscasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		$response = $this->getResponse();

		$req = $this->getRequest();
		$funeral_dir_id = "".$req->getParam("funeral_dir_id");

		$branch_number = $req->getParam("branch_number");

		// 1. select FD record for funeral_dir_id
		// 2. get FD_ids from that record
		// 3. select cases where case's FD id is in FD_ids and vend them.
		$users = new Users();
		$results =  $users->getFuneralDirectorForFDMSLicenseNum( "$funeral_dir_id" );

		$fdUserProfile = $results['rows'][0];
		// on load, the branches and FD_ids are parallel arrays.
		// so we should be able to explode them both and combine them into a combo
		// array with branch_id as the key and FD_id as the value.  *then* we should be
		// able to pick out the FDMS FD id for the currently selected branch
		// (which we ought to be passing in anyway).  change in ksadmingrids.js
		// to modify the cases URL to include the branch ID (defaulting to EMPTY)
		// as well as the FD_id (defaulting to -1)

		$branches = explode( ",", $fdUserProfile["branchnums"] );
		$FDids = explode(",", $fdUserProfile["FD_ids"] );

		$indexed = array_combine( $branches, $FDids );
		$FDMS_fd_id = $indexed[$branch_number];

		$resultsArray = array();
		$resultsArray['identifier'] = 'id';

		$Cases = new FDMSCases();
		if($branch_number != -1 && $Cases)
		{
			$fcresults = $Cases->getCasesForFDMSFuneralDirIdAtBranch($FDMS_fd_id, $branch_number);
			$funeral_cases = $fcresults['rows'];
			$grid_cases = array();
			foreach( $funeral_cases as $case )
			{
				$status = $case['status'];
				$case_num = $case['FDMS_case_num'];

				$name = $case['decedent_lname'].", ";
				$name .= $case['decedent_fname'];
				if(!empty($case['decedent_mname']))
				$name .= " " . $case['decedent_mname'];

				$dob = $case['decedent_dob'];
				$dod = $case['decedent_dod'];

				$residence = $case['decedent_city'].", ".$case['decedent_state'];
				$contact_fname = $case['contact_fname'];
				$contact_mname = $case['contact_mname'];
				$contact_lname = $case['contact_lname'];
				$informant = $contact_fname;
				if(trim($contact_mname)!="") $informant .= " $contact_mname";
				$informant .= " $contact_lname";

				$grid_cases[] = array(
				'id'=>$case['FDMS_vitals_id'],
				'case_num'=>$case_num,
				'status'=>$status,
				'name'=>$name,
				'dob'=>$dob,
				'dod'=>$dod,
				'informant'=>$informant,
				'residence'=>$residence
				);
			}
		}
		else
		{
			$grid_cases = array();
		}

		$resultsArray['items'] = $grid_cases;
		echo json_encode($resultsArray);
	}

	public function kscashadvancesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		// get list of cash advances
		$cashAdvanceItemsMgr = new CashAdvances();
		$cashAdvanceItems = $cashAdvanceItemsMgr->getItems();

		$results = array();
		$results['identifier'] = 'id';
		$results['items'] = $cashAdvanceItems;

		// format list as JSON array
		// $this->view->cash_advances = $json_array;
		echo json_encode($results);
	}

	public function ksmerchandiseAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$itemsMgr = new PriorityMerchandiseItems();
		$pmItems = $itemsMgr->getItems();

		// get list of top merchandise items
		// format list as JSON array
		// $this->view->merchandise = $json_array;
		$results = array();
		$results['identifier'] = 'id';
		$results['items'] = $pmItems;

		echo json_encode($results);
	}

	public function fdgrouppreregcasesAction()
	{
		$ns = new Zend_Session_Namespace("VAS");

		//        if(!isset($ns->fd_id))
		//           $this->_redirect('/index/login');

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		$fdid = $ns->fd_id;
		$fhid = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$cases = new FDMSCases();

		$req = $this->getRequest();

		$group_ids_str = $req->getParam('group_ids');
		if(!isset($group_ids_str)) $group_ids_str = "-1";
		$results = $cases->getPreregCasesAssignedToGroup($group_ids_str);

		$preregCases = $results['rows'];

		$prereg_cases = array();
		foreach( $preregCases as $case )
		{
			$status = $case['status'];

			if($status == "PREREG")
			$case_num = $case['FDMS_vitals_id'];
			else
			$case_num = $case['FDMS_case_num'];

			$name = $case['decedent_lname'].", ";
			$name .= $case['decedent_fname'];
			if(!empty($case['decedent_mname']))
			$name .= " " . $case['decedent_mname'];

			$dob = $case['decedent_DOB'];
			$dod = $case['decedent_DOD'];

			$residence = $case['decedent_city'].", ".$case['decedent_state'];

			$prereg_cases[] = array(
			'id'=>$case['id'],
			'FDMS_case_num'=>$case_num,
			'status'=>$status,
			'name'=>$name,
			'dob'=>$dob,
			'dod'=>$dod,
			'residence'=>$residence
			);
		}

		$results = array();
		$results['identifier'] = 'id';
		$results['items'] = $prereg_cases;

		echo json_encode($results);
	}

	public function fdpreregcasesAction()
	{
		$ns = new Zend_Session_Namespace("VAS");

		//        if(!isset($ns->fd_id))
		//           $this->_redirect('/index/login');

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		$fdid = $ns->fd_id;
		$fhid = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$cases = new FDMSCases();

		$req = $this->getRequest();

		$funeral_dir_id = $req->getParam('funeral_dir_id');

		//ADDME - get list of branches this FD works at
		//ADDME - pick first branch and get its group number

		//FIXME - add a getPreregCasesForGroup( $groupNumber )
		// that works the same as the general getPreregCases() call

		$results = $cases->getPreregCases();
		$preregCases = $results['rows'];

		$prereg_cases = array();
		foreach( $preregCases as $case )
		{
			$status = $case['status'];

			if($status == "PREREG")
			$case_num = $case['FDMS_vitals_id'];
			else
			$case_num = $case['FDMS_case_num'];

			$name = $case['decedent_lname'].", ";
			$name .= $case['decedent_fname'];
			if(!empty($case['decedent_mname']))
			$name .= " " . $case['decedent_mname'];

			$dob = $case['decedent_DOB'];
			$dod = $case['decedent_DOD'];

			$residence = $case['decedent_city'].", ".$case['decedent_state'];

			$prereg_cases[] = array(
			'id'=>$case['id'],
			'FDMS_case_num'=>$case_num,
			'status'=>$status,
			'name'=>$name,
			'dob'=>$dob,
			'dod'=>$dod,
			'residence'=>$residence
			);
		}

		$results = array();
		$results['identifier'] = 'id';
		$results['items'] = $prereg_cases;

		echo json_encode($results);
	}

	public function fdpendingcasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		$fdid = $ns->fd_id;
		$fhid = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$funeral_dir_id = $req->getParam('funeral_dir_id');

		$cases = new FDMSCases();

		// note - since we're doing this from the FD Dashboard, we have
		// the FD record as $ns->user_profile.  that means we can get FD_ids
		// and use that to get the cases this FD handles.
		$fdIDlist = $ns->user_profile['FD_ids'];
		$results = $cases->getOpenCasesForFDMSFuneralDirIds( $fdIDlist );

		//        $results = $cases->getPendingCasesForFuneralDirector( $funeral_dir_id );
		//$results = $cases->getOpenCasesForBranches( $ns->user_profile->branches );
		$pendingCases = $results['rows'];

		$pending_cases = array();
		foreach( $pendingCases as $case )
		{
			$status = $case['status'];

			if($status == "PREREG")
			$case_num = $case['FDMS_vitals_id'];
			else
			$case_num = $case['FDMS_case_num'];

			$name = $case['decedent_lname'].", ";
			$name .= $case['decedent_fname'];
			if(!empty($case['decedent_mname']))
			$name .= " " . $case['decedent_mname'];

			$dob = $case['decedent_dob'];
			$dod = $case['decedent_dod'];

			$branch_id = $case['branch_id'];

			$residence = $case['decedent_city'].", ".$case['decedent_state'];
			$contact_fname = $case['contact_fname'];
			$contact_mname = $case['contact_mname'];
			$contact_lname = $case['contact_lname'];
			$informant = $contact_fname;
			if(trim($contact_mname)!="") $informant .= " $contact_mname";
			$informant .= " $contact_lname";

			$pending_cases[] = array(
			'case_num'=>$case['id'],
			'FDMS_case_num'=>$case_num,
			'branch_num'=>$case['branch_num'],
			'branch_id' => $branch_id,
			'status'=>$status,
			'name'=>$name,
			'dob'=>$dob,
			'dod'=>$dod,
			'informant'=>$informant
			);
		}

		$results = array();
		$results['identifier'] = 'FDMS_case_num';
		$results['items'] = $pending_cases;

		echo json_encode($results);
	}

	public function fdfinishedcasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$ns = new Zend_Session_Namespace("VAS");

		$this->_fd_id = $ns->fd_id;
		$this->_fh_id = $ns->fh_id;

		$fdid = $ns->fd_id;
		$fhid = $ns->fh_id;

		if(!$this->isLoggedIn())
		$this->_redirect('/index/login');

		$req = $this->getRequest();
		$funeral_dir_id = $req->getParam('funeral_dir_id');

		$cases = new FDMSCases();

		//$results = $cases->getFinishedCasesForBranches( $ns->user_profile->branches );
		//        $results = $cases->getFinishedCasesForFuneralDirector( $funeral_dir_id );
		$fdIDlist = $ns->user_profile['FD_ids'];
		$results = $cases->getFinishedCasesForFDMSFuneralDirIds( $fdIDlist );

		$finishedCases = $results['rows'];

		$finished_cases = array();
		foreach( $finishedCases as $case )
		{
			$status = $case['status'];

			if($status == "PREREG")
			$case_num = $case['FDMS_vitals_id'];
			else
			$case_num = $case['FDMS_case_num'];

			$name = $case['decedent_lname'].", ";
			$name .= $case['decedent_fname'];
			if(!empty($case['decedent_mname']))
			$name .= " " . $case['decedent_mname'];

			$dob = $case['decedent_dob'];
			$dod = $case['decedent_dod'];

			$residence = $case['decedent_city'].", ".$case['decedent_state'];
			$contact_fname = $case['contact_fname'];
			$contact_mname = $case['contact_mname'];
			$contact_lname = $case['contact_lname'];
			$informant = $contact_fname;
			if(trim($contact_mname)!="") $informant .= " $contact_mname";
			$informant .= " $contact_lname";

			$finished_cases[] = array(
			'id'=>$case['id'],
			'FDMS_case_num'=>$case_num,
			'status'=>$status,
			'name'=>$name,
			'dob'=>"$dob",
			'dod'=>"$dod",
			'informant'=>$informant
			);
		}

		$results = array();
		$results['identifier'] = 'FDMS_case_num';
		$results['items'] = $finished_cases;

		echo json_encode($results);
	}

	public function vasmerchandiseforbranchAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$branch_num = $request->getParam('branch_number');

		$branch_merch_items = array();

		if(strlen($branch_number)>0)
		{
			$merchResults = FDMSAPIcalls::getMerchandiseForBranchId($branch_number);

			$rowNum = 1;
			$merchRows = $merchResults['rows'];
			foreach( $merchRows as $row )
			{
				$merchItem = array();
				$merchItem['inventory_master_id'] = $row['price_list_id'];
				$merchItem['item_category'] = $row['item_category'];
				$merchItem['item_description'] = $row['item_description'];
				$merchItem['item_amount'] = $row['item_amount'];
				$merchItem['row_num'] = $rowNum;
				//				$branch_merch_items[] = $merchItem;
				$row['rowNum'] = $rowNum;
				$branch_merch_items[] = $row;
				$rowNum++;
			}
		}

		$results = array();
		$results['identifier'] = 'row_num';
		$results['items'] = $branch_merch_items;

		echo json_encode($results);
	}

	public function vascashadvancesforlocaleAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$locale_id = $request->getParam('locale_id');

		$cash_advances = array();

		if(strlen($locale_id)>0)
		{
			$advancesResults = FDMSAPIcalls::getCashAdvancesForLocaleId($locale_id);

			$rowNum = 1;
			$advancesRows = $advancesResults['rows'];
			foreach( $advancesRows as $row )
			{
				$advItem = array();
				$advItem['item_category'] = $row['item_category'];
				$advItem['price_list_id'] = $row['price_list_id'];
				$advItem['item_description'] = $row['item_description'];
				$advItem['item_amount'] = $row['item_amount'];
				$advItem['row_num'] = $rowNum;
				$cash_advances[] = $advItem;
				$rowNum++;
			}
		}

		$results = array();
		$results['identifier'] = 'row_num';
		$results['items'] = $cash_advances;

		echo json_encode($results);
	}

	public function vasservicesforlocaleAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$locale_id = $request->getParam('locale_id');

		$locale_services = array();

		if(strlen($locale_id)>0)
		{
			$servicesResults = FDMSAPIcalls::getServicesForLocaleId($locale_id);

			$rowNum = 1;
			$servicesRows = $servicesResults['rows'];
			foreach( $servicesRows as $row )
			{
				$serviceItem = array();
				$serviceItem['item_category'] = $row['item_category'];
				$serviceItem['price_list_id'] = $row['price_list_id'];
				$serviceItem['item_description'] = $row['item_description'];
				$serviceItem['item_amount'] = $row['item_amount'];
				$serviceItem['row_num'] = $rowNum;
				$locale_services[] = $serviceItem;
				$rowNum++;
			}
		}

		$results = array();
		$results['identifier'] = 'row_num';
		$results['items'] = $locale_services;

		echo json_encode($results);
	}

	public function vaspackagesforlocaleAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$locale_id = $request->getParam('locale_id');

		$locale_packages = array();

		if(strlen($locale_id)>0)
		{
			$packagesResults = FDMSAPIcalls::getPackagesForLocaleId($locale_id);

			$rowNum = 1;
			$packagesRows = $packagesResults['rows'];
			foreach( $packagesRows as $row )
			{
				$packageItem = array();
				$packageItem['package_id'] = $row['package_id'];
				$packageItem['package_status'] = $row['package_status'];
				$packageItem['package_type'] = $row['package_type'];

				// now make a second API call to get the package detail info to get these
				$pkgId = $row['package_id'];
				$res2 = FDMSAPIcalls::getPackageDetailsForPackageId($pkgId);
				$details_row = $res2['rows'][0];

				$packageItem['price_list_id'] = $details_row['price_list_id'];
				$packageItem['item_description'] = $details_row['item_description'];
				$packageItem['item_amount'] = $details_row['item_amount'];

				$packageItem['row_num'] = $rowNum;

				$locale_packages[] = $packageItem;

				$rowNum++;
			}
		}

		$results = array();
		$results['identifier'] = 'row_num';
		$results['items'] = $locale_packages;

		echo json_encode($results);
	}

	/////////////////////////////////////////////////////////////////////////////
	// methods for caterer and florist editing
	public function floristsandcollectionsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$floristsModel = new Florists();


		$branch_number = $request->getParam('branch_number');
		$floristsandcollections = $floristsModel->getFloristsAndCollectionsForBranch( $branch_number );

		$florists_str = $floristsandcollections[0];

		if(null != $florists_str)
		{
			$florists = simplexml_load_string( $florists_str );

			$floristsArray = array();
			foreach($florists->florist as $ff)
			{
				$florist_row = array();
				$florist_row["name"] = "".$ff->name;
				$florist_row["address"] = "".$ff->address;
				$florist_row["city"] = "".$ff->city;
				$florist_row["state"] = "".$ff->state;
				$florist_row["zip"] = "".$ff->zip;
				$florist_row["phone"] = "".$ff->phone;
				$florist_row["fax"] = "".$ff->fax;
				$florist_row["email"] = "".$ff->email;

				$collections = array();
				if($ff->collections->collection)
				{
					foreach( $ff->collections->collection as $collection )
					{
						$collection_row = array();

						$collection_row['name'] = "".$collection->name;
						$collection_row['description'] = "".$collection->description;
						$collection_row['units'] = "".$collection->units;
						$collection_row['price'] = "".$collection->price;
						$collections[] = $collection_row;
					}
				}
				$florist_row['collections'] = $collections;
				$floristsArray[] = $florist_row;
			}
		}

		echo json_encode($floristsArray);
	}

	public function updatefloristsandcollectionsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$floristsModel = new Florists();

		if( $request->isPost() )
		{
			$p = $request->getParams();

			$branch_number = $request->getParam('branch_number');
			$floristsXML = stripslashes($request->getParam('floristsXML'));

			// now we would write these to a db
			$floristsModel->setFloristsAndCollectionsForBranch( $floristsXML, $branch_number);
			echo json_encode( array("status"=>"OK", "xml"=>$floristsXML ));
		}
	}

	public function caterersandmenusAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		$request = $this->getRequest();
		$caterersModel = new Caterers();

		$branch_number = $request->getParam('branch_number');
		$caterersandmenus = $caterersModel->getCaterersAndMenusForBranch($branch_number);

		//$results['bigxml'] = $caterersandmenus[0];
		//echo json_encode($results);
		$caterers_str = $caterersandmenus[0];
		$caterersArray = array();
		if(null != $caterers_str)
		{
			$caterers = simplexml_load_string( $caterersandmenus[0] );
			foreach($caterers->caterer as $cc)
			{
				$caterer_row = array();
				$caterer_row["name"] = "".$cc->name;
				$caterer_row["address"] = "".$cc->address;
				$caterer_row["city"] = "".$cc->city;
				$caterer_row["state"] = "".$cc->state;
				$caterer_row["zip"] = "".$cc->zip;
				$caterer_row["phone"] = "".$cc->phone;
				$caterer_row["fax"] = "".$cc->fax;
				$caterer_row["email"] = "".$cc->email;

				$menus = array();
				if($cc->menus->menu)
				{
					foreach( $cc->menus->menu as $menu )
					{
						$menu_row = array();

						$menu_row['name'] = "".$menu->name;
						$menu_row['description'] = "".$menu->description;
						$menu_row['units'] = "".$menu->units;
						$menu_row['price'] = "".$menu->price;
						$menus[] = $menu_row;
					}
				}
				$caterer_row['menus'] = $menus;
				$caterersArray[] = $caterer_row;
			}
		}

		echo json_encode($caterersArray);
	}

	public function updatecaterersandmenusAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$caterersModel = new Caterers();

		if( $request->isPost() )
		{
			$branch_number = $request->getParam('branch_number');
			$caterersXML = stripslashes($request->getParam('caterersXML'));
			// now we would write these to a db
			$caterersModel = new Caterers();
			$caterersModel->setCaterersAndMenusForBranch( $caterersXML, $branch_number);
			echo json_encode( array("status"=>"OK", "xml"=>$caterersXML ));
		}
	}

	public function tributepackagesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();

		$tributesModel = new TributePackages();

		$tributepackagesarray = array();
		foreach( TributePackages::$_tributes as $tribute_name )
		{
			$tributepackage = array();
			$tributepackage['name'] = $tribute_name;
			$tributepackage['bullet_points'] = array();
			$results = $tributesModel->getBulletPointsForTribute( $tribute_name );
			$package =  $results['rows'][0];
			$xmlstr = $package['bigxml'];
			if(isset($xmlstr))
			{
				$xmlpkg = simplexml_load_string( $xmlstr );
				foreach( $xmlpkg->bulletpoint as $bp )
				{
					$tributepackage['bullet_points'][] = $bp;
				}
			}
			$tributepackagesarray[] = $tributepackage;
		}

		echo json_encode($tributepackagesarray);
	}

	public function updatetributepackagesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();

		if( $request->isPost() )
		{
			$tributesModel = new TributePackages();
			$tributesXML = stripslashes($request->getParam('tributesXML'));
			$tributes = simplexml_load_string( $tributesXML );
			foreach( $tributes->tribute as $tribute )
			{
				$tribute_name = $tribute->name;
				$bpXML = $tribute->bulletpoints->asXML();
				$results = $tributesModel->setBulletPointsForTribute( $bpXML, $tribute_name );
			}
			echo json_encode( array("status"=>"OK", "xml"=>$tributesXML, "results"=>$results ));
		}
	}

	public function importfuneralhomes()
	{
		$output_msg = array();

		// #1 - fetch funeral homes
		$results = FDMSAPIcalls::getKeystoneFuneralHomes();
		if(count($results['rows'])<1)
		{
			$output_msg['status'] = "FAILED";
			$output_msg['reason'] = "Failed fetching Keystone funeral homes from FDMS";
			return;
		}

		$fetchedFuneralHomes = array();
		foreach( $results['rows'] as $row )
		$fetchedFuneralHomes[$row['branch_number']] = $row;

		$funeralHomesModel = new FuneralHomes();

		$results = $funeralHomesModel->getFuneralHomes();
		if($results['status'] != "SUCCEEDED")
		{
			$output_msg['status'] = "FAILED";
			$output_msg['reason'] = "Failed loading Keystone funeral homes from VAS";
			return $output_msg;
		}
		$storedFuneralHomes = array();
		foreach( $results['rows'] as $row )
		$storedFuneralHomes[$row['branch_number']] = $row;

		$newFuneralHomes = array_diff_key( $fetchedFuneralHomes, $storedFuneralHomes );

		foreach( $newFuneralHomes as &$newFH )
		{
			$results = FDMSAPIcalls::getFuneralHomeDetails( $newFH['branch_number'] );
			if($results['status'] == "SUCCEEDED")
			{
				$row = $results['rows'][0];
				$newFH['locale_id'] = $row['locale_id'];
				$newFH['name'] = $row['name'];
				$newFH['addr1'] = $row['addr1'];
				$newFH['city'] = $row['city'];
				$newFH['state'] = $row['state'];
				$newFH['zip'] = $row['zip'];
				$newFH['phone'] = $row['phone'];
				$newFH['url'] = $row['url'];
			}
			$funeralHomesModel->insert( $newFH );
		}

		$output_msg['status'] = "SUCCEEDED";
		$output_msg['rows_affected'] = count($newFuneralHomes);
		$output_msg['rows'] = $newFuneralHomes;

		return $output_msg;
	}

	public function importfhsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		$results = $this->importfuneralhomes();
		echo json_encode( $results );
	}

	public function importnewdirectorsAction()
	{
		$main_results = array();

		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$users = new Users();
		$request = $this->getRequest();
		if($request->isGet())
		{
			$branch_number = $request->getParam('branch_number');
			if(!empty($branch_number))
			{
				// get funeral home info for branch id to get state (to prepend license number)
				$funeralHomes = new FuneralHomes();

				$results = $funeralHomes->getHomeByFDMSId( "$branch_number" );
				if($results['status'] == "SUCCEEDED")
				$homeProfile = $results['rows'][0];
				else
				{
					// bounce out with message indicating "no such home"
					$main_results['status'] = 'FAILED';
					$main_results['reason'] = "Branch Number '$branch_number' does not exist";
					echo json_encode( $main_results );
					return;
				}

				$fhState = $homeProfile['state'];
				$fetchedFds = array();
				$np = new nameParser();

				// get funeral directors for that branch
				$results = FDMSAPIcalls::getFuneralDirectors( $branch_number );
				if($results['status'] != "SUCCEEDED")
				{
					$main_results['status'] = 'FAILED';
					$main_results['reason'] = "Failed to fetch funeral directors for branch number $branch_number from FDMS";
					echo json_encode( $main_results );
					return;
				}

				if(count($results['rows']) < 1)
				{
					$main_results['status'] = 'NO_ARRANGERS';
					$main_results['reason'] = "Found no funeral directors for branch $branch_id from FDMS";
					echo json_encode( $main_results );
					return;
				}

				$main_results['changes'] = array();

				foreach( $results['rows'] as $row )
				{
					$fdms_license_num = trim($row['license_number']);
					$license_num = trim($fhState . "-".$row['license_number']);

					if(empty($fdms_license_num))
					continue;

					$profile = array();

					$profile['FD_ids'] = $row['id'];
					$profile['branches'] = "{$homeProfile['branch_id']}";
					$profile['branchnums'] = "$branch_number";
					$profile['full_name'] = $row['full_name'];
					$profile['fname'] = '';
					$profile['mname'] = '';
					$profile['lname'] = '';
					$profile['username'] = '';
					$profile['password'] = '';
					$profile['FDMS_license_number'] = $license_num;

					$fetchedFds[$license_num] = $profile;

					$full_name = $profile['full_name'];
					$fdId = $row['id'];

					$np->setFullName($full_name);
					$np->parse();

					if($users->funeralDirExistsWithLicenseNumber( $license_num))
					{
						if(!$users->funeralDirExistsAtBranch( $license_num, $branch_number ))
						{
							$results = $users->addBranchInfoToFuneralDirector( $fdId, $branch_number, $license_num );
							echo json_encode($results);
							if($results['status'] == "SUCCEEDED")
							$main_results['changes'][] = "Added funeral arranger '$full_name' to branch '$branch_number' for license $license_num.";
							else
							{
								$main_results['changes'][] = "Unable to add funeral arranger '$full_name' to branch '$branch_number' for license $license_num.";
							}

						}
					}
					else
					{
						$profile['fname'] = $np->getFirstName();
						$profile['mname'] = $np->getMiddleName();
						$profile['lname'] = $np->getLastName();

						// username and password = arranger{$fdId}?
						$username = sprintf("arranger%05d", $fdId);
						$profile['username'] = $username;
						$profile['password'] = $username;

						$results = $users->createFuneralDirectorUser( $profile );
						if($results['status'] == "SUCCEEDED")
						$main_results['changes'][] = "Created funeral arranger '$full_name' at branch '$branch_id' for license $license_num.";
						else
						{
							$main_results['changes'][] = "Unable to create funeral arranger '$full_name' at branch '$branch_id' for license $license_num.";
						}

					}
				}
			}
		}

		echo json_encode( $main_results );
	}

	public function computenewcasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$main_results = array();

		$storedCases = array();
		$fetchedCases = array();

		$cases = new FDMSCases();
		$request = $this->getRequest();
		if($request->isGet())
		{
			$arranger_id = $request->getParam('arranger_id');
			if(!empty($arranger_id))
			{
				$fetchedCases = array();
				$fd_id = $arranger_id;
				$results = FDMSAPIcalls::getCasesForDirector( $fd_id );
				if($results['status'] != "SUCCEEDED")
				{
					$main_results['status'] = 'FAILED';
					$main_results['reason'] = "Failed getting cases for arranger $arranger__id from FDMS";
					echo json_encode( $main_results );
					return;
				}

				foreach( $results['rows'] as &$row )
				{
					$vitalsId = $row['FDMS_vitals_id'];
					$fdms_case_num = $row['FDMS_case_num'];
					$fetchedCases[$fdms_case_num]['vitalsId'] = $vitalsId;
					$fetchedCases[$fdms_case_num]['fdId'] = $fd_id;
				}
			}

			$fetchedCaseNums = array_keys($fetchedCases);
			$fetchedCaseNumStr = implode( $fetchedCaseNums);

			// take FDMS_case_nums from $cases[] and diff them with cases for this branch.
			$results = $cases->getOpenAndFinishedCaseIdsForFD( "'$arranger_id'" );
			if($results['status'] != "SUCCEEDED")
			{
				$main_results['status'] = 'FAILED';
				$main_results['reason'] = "Failed getting cases for arranger $arranger_id from VAS";
				echo json_encode( $main_results );
				return;
			}

			foreach( $results['rows'] as $row )
			{
				$fdms_case_num = $row['FDMS_case_num'];
				$storedCases[$fdms_case_num] = $row['FDMS_vitals_id'];
			}

			$storedCaseNums = array_keys($storedCases);
			$storedCaseNumStr = implode( $storedCaseNums);

			$newCases = array_diff_key( $fetchedCases, $storedCases );
			$newCasesNumStr = implode( ",", array_keys($newCases) );

			$newcasetuples = array();
			foreach( $newCases as $casenum=>$tuple )
			{
				$newcasetuples[] = array("casenum"=>$casenum, "vitalsid"=>$tuple['vitalsId']);
			}

			$main_results['newcasetuples'] = $newcasetuples;
		}

		echo json_encode( $main_results );
	}

	public function importnewcaseAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$output_msg = array();
		$users = new Users();
		$homes = new FuneralHomes();
		$cases = new FDMSCases();

		$request = $this->getRequest();
		if($request->isGet())
		{
			$arrangerId = $request->getParam('arranger_id');
			$vitalsId = $request->getParam('vitals_id');
			$branch_number = $request->getParam('branch_number');

			if(empty($vitalsId))
			{
				$output_msg['status'] = "FAILED";
				$output_msg['details'] = "Missing vitals id";
				echo json_encode($output_msg);
				return;
			}

			if(empty($arrangerId))
			{
				$output_msg['status'] = "FAILED";
				$output_msg['details'] = "Missing arranger id";
				echo json_encode($output_msg);
				return;
			}

			// use $arrangerId to fetch branch number to add to case
			$results = $users->getFuneralDirectorForFDMSId( $arrangerId );
			if($results['status'] != "SUCCEEDED")
			{
				$output_msg['status'] = "FAILED";
				$output_msg['details'] = "Unable to fetch arranger for id $arrangerId";
				echo json_encode($output_msg);
				return;
			}

			$arranger = $results['rows'][0];

			// use branch number to fetch funeral home for branch id and locale id
			$results = $homes->getHomeByFDMSId( $branch_number );
			if($results['status'] != "SUCCEEDED")
			{
				$output_msg['status'] = "FAILED";
				$output_msg['details'] = "Unable to fetch funeral home info for id $branch_number";
				echo json_encode($output_msg);
				return;
			}

			$branch = $results['rows'][0];
			$branch_id = $branch['branch_id'];
			// fetch case for vitals id
			$results = FDMSAPIcalls::getCaseDetails( $vitalsId );
			$rows = $results['rows'];
			// data is in $rows[0];
			$case = $rows[0];

			$case['branch_num'] = $branch_number;
			$case['branch_id'] = $branch['branch_id'];
			$case['status'] = 'OPEN';
			$case['FDMS_funeral_director_id'] = $arrangerId;

			$results = $cases->insertCase( $case, $branch_id, $branch_number );
			if($results['status'] == "SUCCEEDED")
			{
				$output_msg['changes'][] = "Added case '$case_num' for branch '$branch_number'.";
			}
			else
			{
				$output_msg['changes'][] = "Unable to add case '$case_num' for branch '$branch_number'.";
				$output_msg['results'] = $results;
			}
		}

		echo json_encode( $output_msg );
	}

	public function importfuneraldirectorsandcasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		// input - funeral home branch number
		// output - status indicator

		$output_msg = array();

		$cases = new FDMSCases();
		$users = new Users();
		$request = $this->getRequest();
		if($request->isGet())
		{
			$branch_number = $request->getParam('branch_number');
			if(!empty($branch_number))
			{
				// get funeral home info for branch id to get state (to prepend license number)
				$funeralHomes = new FuneralHomes();

				$results = $funeralHomes->getHomeByBranchNumber( "$branch_number" );
				if($results['status'] == "SUCCEEDED")
				$homeProfile = $results['rows'][0];
				else
				{
					// bounce out with message indicating "no such home"
					$output_msg['status'] = 'FAILED';
					$output_msg['reason'] = "Branch Number '$branch_number' does not exist";
					echo json_encode( $output_msg );
					return;
				}

				$fhState = $homeProfile['state'];
				$fetchedFds = array();
				$np = new nameParser();

				// get funeral directors for that branch
				$results = FDMSAPIcalls::getFuneralDirectors( $branch_number );
				if($results['status'] != "SUCCEEDED")
				{
					$output_msg['status'] = 'FAILED';
					$output_msg['reason'] = "Failed to fetch funeral directors for branch number $branch_number from FDMS";
					echo json_encode( $output_msg );
					return;
				}

				if(count($results['rows']) < 1)
				{
					$output_msg['status'] = 'NO_ARRANGERS';
					$output_msg['reason'] = "Found no funeral directors for branch $branch_id from FDMS";
					echo json_encode( $output_msg );
					return;
				}

				$output_msg['changes'] = array();

				foreach( $results['rows'] as $row )
				{
					$fdms_license_num = trim($row['license_number']);
					$license_num = trim($fhState . "-".$row['license_number']);

					if(empty($fdms_license_num))
					continue;

					$profile = array();

					$profile['FD_ids'] = $row['id'];
					$profile['branches'] = "$branch_number";
					$profile['full_name'] = $row['full_name'];
					$profile['fname'] = '';
					$profile['mname'] = '';
					$profile['lname'] = '';
					$profile['username'] = '';
					$profile['password'] = '';
					$profile['FDMS_license_number'] = $license_num;

					$fetchedFds[$license_num] = $profile;

					$full_name = $profile['full_name'];
					$fdId = $row['id'];

					$np->setFullName($full_name);
					$np->parse();

					if($users->funeralDirExistsWithLicenseNumber( $license_num))
					{
						if(!$users->funeralDirExistsAtBranch( $license_num, $branch_number ))
						{
							$results = $users->addBranchInfoToFuneralDirector( $fdId, $branch_number, $license_num );
							echo json_encode($results);
							if($results['status'] == "SUCCEEDED")
							$output_msg['changes'][] = "Added funeral arranger '$full_name' to branch '$branch_number' for license $license_num.";
							else
							{
								$output_msg['changes'][] = "Unable to add funeral arranger '$full_name' to branch '$branch_number' for license $license_num.";
							}
						}
					}
					else
					{
						// if we create the FD profile, we need to parse the full_name
						// and generate a username and password.

						$profile['fname'] = $np->getFirstName();
						$profile['mname'] = $np->getMiddleName();
						$profile['lname'] = $np->getLastName();

						// username and password = arranger{$fdId}?
						$username = sprintf("arranger%05d", $fdId);
						$profile['username'] = $username;
						$profile['password'] = $username;

						$results = $users->createFuneralDirectorUser( $profile );
						if($results['status'] == "SUCCEEDED")
						$output_msg['changes'][] = "Created funeral arranger '$full_name' at branch '$branch_id' for license $license_num.";
						else
						{
							$output_msg['changes'][] = "Unable to create funeral arranger '$full_name' at branch '$branch_id' for license $license_num.";
						}
					}
				}

				$fetchedCases = array();
				$branchNumbers = array();

				foreach( $fetchedFds as $license_number=>$fdProfile )
				{
					$fd_id = $fdProfile['FD_ids'];
					$fullname = $fdProfile['full_name'];
					$results = FDMSAPIcalls::getCasesForDirector( $fd_id );
					if($results['status'] != "SUCCEEDED")
					{
						$output_msg['status'] = 'FAILED';
						$output_msg['reason'] = "Failed getting cases for branch/FD $branch_id/$fd_id from FDMS";
						echo json_encode( $output_msg );
						return;
					}

					foreach( $results['rows'] as &$row )
					{
						$vitalsId = $row['FDMS_vitals_id'];
						$fdms_case_num = $row['FDMS_case_num'];
						$fetchedCases[$fdms_case_num]['vitalsId'] = $vitalsId;
						$fetchedCases[$fdms_case_num]['fdId'] = $fd_id;
						$branchNumbers[$vitalsId] = $branch_number;
					}
				}

				$fetchedCaseNums = array_keys($fetchedCases);
				$fetchedCaseNumStr = implode( $fetchedCaseNums);

				// take FDMS_case_nums from $cases[] and diff them with cases for this branch.
				$results = $cases->getOpenAndFinishedCaseIdsForBranches( "'$branch_number'" );
				if($results['status'] != "SUCCEEDED")
				{
					$output_msg['status'] = 'FAILED';
					$output_msg['reason'] = "Failed getting cases for branch $branch_id from VAS";
					echo json_encode( $output_msg );
					return;
				}

				foreach( $results['rows'] as $row )
				{
					$fdms_case_num = $row['FDMS_case_num'];
					$storedCases[$fdms_case_num] = $row['FDMS_vitals_id'];
				}

				$storedCaseNums = array_keys($storedCases);
				$storedCaseNumStr = implode( $storedCaseNums);

				// then retrieve case detail info for the case numbers in the uniq'd list and
				// import them into db.  we will have to assume that the case numbers are unique.
				$newCases = array_diff_key( $fetchedCases, $storedCases );
				$newCasesNumStr = implode( ",", array_keys($newCases) );

				foreach( $newCases as $case_num=>$caseNuggets )
				{
					$vitalsId = $caseNuggets['vitalsId'];
					$results = FDMSAPIcalls::getCaseDetails( $vitalsId );
					$rows = $results['rows'];
					if(count($rows)>0)
					{
						// data is in $rows[0];
						$case = $rows[0];
						// need locale_id as well.  have to do that using the FuneralArrangerId
						// in the case record and looking up the User/FD for that id, or mapping
						// the branch_id to the locale_id?  yeah, latter.
						$case['branch_id'] = $branch_id;
						$case['branch_number'] = $branch_number;
						$case['status'] = 'OPEN';
						$case['FDMS_funeral_director_id'] = $caseNuggets['fdId'];
						$results = $cases->insertCase( $case, $branch_id, $branch_num );
						if($results['status'] == "SUCCEEDED")
						{
							$output_msg['changes'][] = "Added case '$case_num' for branch '$branch_number'.";
						}
						else
						{
							$output_msg['changes'][] = "Unable to add case '$case_num' for branch '$branch_number'.";
						}
					}
				}
			}

			$output_msg['status'] = 'OK';
			$output_msg['reason'] = "";
			echo json_encode( $output_msg );
		}
		else
		{
			// output is "Invalid request type"
			$output_msg['status'] = 'FAILED';
			$output_msg['reason'] = "Invalid request type";
			echo json_encode( $output_msg );
		}
	}

	///////// utility action to load data brought over in a lump from FDMS
	public function importcsvdataAction()
	{
		$fh_import_filepath = "/home/cwoodard/Desktop/homes.csv";
		$fd_import_filepath = "/home/cwoodard/Desktop/fds.csv";
		$case_import_filepath = "/home/cwoodard/Desktop/cases.csv";

		// delete everything
		$fhModel = new FuneralHomes();
		$fhModel->delete("TRUE");
		$users = new Users();
		$users->delete("role_name != 'Admin'");

		$casesModel = new FDMSCases();
		$casesModel->delete("TRUE");

		$fh_fp = fopen( $fh_import_filepath, "r" );
		if(!$fh_fp)
		exit(0);

		$cols = fgetcsv( $fh_fp, 5120, "," );
		while(!feof($fh_fp))
		{
			$vals = fgetcsv( $fh_fp, 5120, "," );
			if($vals != null)
			{
				$row = array_combine( $cols, $vals );
				// now insert this row into VAS funeral homes table
				try {
					$fhModel->insert($row);
				}
				catch(Exception $e)
				{
					Zend_Debug::dump($e);
					exit(0);
				}
			}
		}
		fclose( $fh_fp );

		$fd_fp = fopen( $fd_import_filepath, "r" );
		if(!$fd_fp)
		exit(0);

		$cols = fgetcsv( $fd_fp, 5120, "," );
		$cols[0] = "FDMS_dir_id";

		$fdArray = array();

		while(!feof($fd_fp))
		{
			$vals = fgetcsv( $fd_fp, 5120, "," );
			if($vals != null)
			{
				$row = array_combine( $cols, $vals );
				$fdArray[] = $row;
			}
		}
		fclose($fd_fp);

		// now that we have the FDs in an array, we sort them by license_number.
		// username = keystoneFD<nnnn>
		// password = same as username at first
		usort( $fdArray, 'fdLicenseCompare' );
		$last_license_number = $fdArray[0]['license_number'];
		$lastRow = $fdArray[0];

		$userNum = 1;

		$fdIdArray = array();
		$fhIdArray = array();
		foreach( $fdArray as $fdRow )
		{
			echo $last_license_number.", ".$fdRow['license_number'].", ".$fdRow['branch_id'].", ".$fdRow["full_name"]."<br>";

			if($last_license_number != $fdRow['license_number'])
			{
				// 1. implode the FD and FH id arrays and add them to $fdRow[]
				$fdIds = implode(",", $fdIdArray);
				$fhIds = implode(",", $fhIdArray);

				echo "*** {$lastRow['full_name']} works at $fhIds<br>";
				// 2. make a new FD user with automatic username and password
				$userName = sprintf("arranger%03d", $userNum);
				$password = $userName;

				$lastRow['username'] = $userName;
				$lastRow['password'] = $password;
				$lastRow['FD_ids'] = $fdIds;
				$lastRow['branches'] = $fhIds;

				//				Zend_Debug::dump($fdRow);

				try {
					$users->createFuneralDirectorUser( $lastRow );
				}
				catch(Exception $e)
				{
					Zend_Debug::dump($fdRow);
					Zend_Debug::dump($e);
					exit(0);
				}

				// 3. update the key break value and reset the arrays
				$last_license_number = $fdRow['license_number'];

				$fdIdArray = array();
				$fhIdArray = array();

				$lastRow = $fdRow;

				++$userNum;
			}

			// 1. take FD id and add it to $fdIdArray[]
			$fdIdArray[] = $fdRow['FDMS_dir_id'];

			// 2. take FH id and add it to $fhIdArray[]
			$fhIdArray[] = $fdRow['branch_id'];
		}

		// 1. implode the FD and FH id arrays and add them to $fdRow[]
		$fdIds = implode(",", $fdIdArray);
		$fhIds = implode(",", $fhIdArray);

		// 2. make a new FD user with automatic username and password

		// now come back and import cases
		$case_fp = fopen( $case_import_filepath, "r" );
		if(!$case_fp)
		exit(0);


		$count=0;
		$rejects=0;
		$cols = fgetcsv( $case_fp, 5120, "," );
		while(!feof($case_fp))
		{
			$vals = fgetcsv( $case_fp, 5120, "," );
			if($vals != null)
			{
				if(count($cols) == count($vals))
				$row = array_combine( $cols, $vals );
				else
				{
					$rejects++;
					echo "number of values does not match number of columns:<br>";
					Zend_Debug::dump($vals);
					continue;
				}

				if(stripos($row['sale_type'], "Trade")) continue;

				echo "case count: $count<br>";
				$count++;
				// now insert this row into VAS funeral dirs table
				try {
					$row['status'] = "OPEN";
					$casesModel->insert($row);
				}
				catch(Exception $e)
				{
					Zend_Debug::dump($e);
					exit(0);
				}
			}
		}
		fclose($case_fp);
		echo "$rejects records rejected<br>";
		exit(0);
	}

	public function whohascasesAction()
	{
	}

	public function formatCase( $case_number )
	{
		$cases = new FDMSCases();
		$caseCashAdvances = new CaseCashAdvances();
		$caseMerchandise = new CaseMerchandise();
		$caseServices = new CaseServices();

		// get master case record
		$results = $cases->getCaseInfoForFDMSCaseNum( $case_number );

		$case = $results['rows'][0];

		// get case services
		$serviceItems = $caseServices->getItemsForCase( $case_number );
		if(null == $serviceItems) $serviceItems = array();

		// get case merchandise
		$merchandiseItems = $caseMerchandise->getItemsForCase( $case_number );
		if(null == $merchandiseItems) $merchandiseItems = array();

		// get case cash advances
		$cashAdvanceItems = $caseCashAdvances->getItemsForCase( $case_number );
		if(null == $cashAdvanceItems) $cashAdvanceItems = array();

		$xmlCase = "<Case>\n";
		$xmlCase .= "<Number>".$case_number."</Number>\n";
		$xmlCase .= "<VitalsId>".$case['FDMS_vitals_id']."</VitalsId>\n";
		$xmlCase .= "<Branch>".$case['branch_num']."</Branch>\n";
		$xmlCase .= "<Status>".$case['status']."</Status>\n";
		$xmlCase .= "<Choice>".$case['choice']."</Choice>\n";
		$xmlCase .= "<Tribute>".$case['tribute_chosen']."</Tribute>\n";
		$xmlCase .= "<Package>".$case['status']."</Package>\n";
		$xmlCase .= "<Casket>".$case['casket']."</Casket>\n";
		$xmlCase .= "<Urn>".$case['urn']."</Urn>\n";
		$xmlCase .= "<Vault>".$case['vault']."</Vault>\n";

		$xmlCase .= "<Services>\n";
		foreach( $serviceItems as $serviceItem )
		{
			$xmlCase .= "<Service>\n";
			$xmlCase .= "<CL>".$serviceItem['line_number']."</CL>\n";
			$xmlCase .= "<ID>".$serviceItem['price_list_id']."</ID>\n";
			$xmlCase .= "<Name>".$serviceItem['item_name']."</Name>\n";
			$xmlCase .= "<Qty>"."1"."</Qty>\n";
			$xmlCase .= "<Price>".$serviceItem['item_amount']."</Price>\n";
			$xmlCase .= "</Service>\n";
		}
		$xmlCase .= "</Services>\n";

		$xmlCase .= "<CashAdvances>\n";
		foreach( $cashAdvanceItems as $cashAdvanceItem )
		{
			$xmlCase .= "<CashAdvance>\n";
			$xmlCase .= "<CL>".$cashAdvanceItem['line_number']."</CL>\n";
			$xmlCase .= "<ID>".$cashAdvanceItem['price_list_id']."</ID>\n";
			$xmlCase .= "<Name>".$cashAdvanceItem['item_name']."</Name>\n";
			$xmlCase .= "<Qty>"."1"."</Qty>\n";
			$xmlCase .= "<Price>".$cashAdvanceItem['item_amount']."</Price>\n";
			$xmlCase .= "</CashAdvance>\n";
		}
		$xmlCase .= "</CashAdvances>\n";

		$xmlCase .= "<Merchandise>\n";
		foreach( $merchandiseItems as $merchandiseItem )
		{
			$xmlCase .= "<MerchItem>\n";
			$xmlCase .= "<CL>".$merchandiseItem['line_number']."</CL>\n";
			$xmlCase .= "<ID>".$merchandiseItem['price_list_id']."</ID>\n";
			$xmlCase .= "<Name>".$merchandiseItem['item_name']."</Name>\n";
			$xmlCase .= "<Qty>".$merchandiseItem['qty']."</Qty>\n";
			$xmlCase .= "<Price>".$merchandiseItem['item_amount']."</Price>\n";
			$xmlCase .= "<Total>".$merchandiseItem['total']."</Total>\n";
			$xmlCase .= "</MerchItem>\n";
		}
		$xmlCase .= "</Merchandise>\n";

		// catering
		$xmlCase .= "<Caterering>\n";
		$xmlCase .= "<Caterer>".$case['caterer']."</Caterer>\n";
		$xmlCase .= "<Menu>".$case['menu']."</Menu>\n";
		$xmlCase .= "<Headcount>".$case['headcount']."</Headcount>\n";
		$xmlCase .= "</Caterering>\n";

		// floral
		$xmlCase .= "<Floral>\n";
		$xmlCase .= "<Florist>".$case['florist']."</Florist>\n";
		$xmlCase .= "<Arrangement>".$case['arrangement']."</Arrangement>\n";
		$xmlCase .= "</Floral>\n";

		$xmlCase .= "<Notes>".$case['general_note']."</Notes>\n";

		$xmlCase .= "</Case>";

		return $xmlCase;
	}

	public function finishedcasenumbersAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$password = $request->getParam('password');

	}

	public function finishedcasenumbersforbranchAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$password = $request->getParam('password');
		$branch_number = $request->getParam('branch_number');

	}

	public function fetchfinishedcaseAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$password = $request->getParam('password');
		$case_number = $request->getParam('case_number');
		if(empty($case_number))
		{
			echo "<Case></Case>";
		}
		else
		{
			echo $this->formatCase( $case_number );
		}
	}

	public function fetchfinishedcasesAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$password = $request->getParam('password');
		$case_numbers_str = $request->getParam('case_numbers');
		if(empty($case_numbers_str))
		{
			echo "<Cases></Cases>";
		}
		else
		{
			$case_numbers = explode(",", $case_number_str);
			$str = "<Cases>\n";
			foreach( $case_numbers as $case_number )
			$str .= formatCase( $case_num );
			$str .= "</Cases>\n";
		}
	}

	public function cateringorderformAction()
	{
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$p = $request->getParams();
		$case_number = $p['case_number'];

		if(isset($case_number))
		{
			$cases = new FDMSCases();
			$results = $cases->getCaseInfoForFDMSCaseNum( $case_number );
			if($results['status'] == "SUCCEEDED")
			{
				$caseInfo = $results['rows'][0];
				$branch_number = $caseInfo['branch_num'];

				$catererStr = $caseInfo['caterer'];
				$menu = $caseInfo['menu'];
				$headcount = $caseInfo['headcount'];

				$caterersModel = new Caterers();
				$caterersStr = $caterersModel->getCaterersAndMenusForBranch( $branch_number );
				$caterers = simplexml_load_string( $caterersStr[0] );

				foreach( $caterers as $caterer )
				{
					if($caterer->name == $catererStr)
					{
						$this->view->caterer = $caterer;
					}
				}

				// get and parse the caterer and menu,
				// add headcount and total
				$this->view->menu = $caseInfo['menu'];
				$this->view->headcount = $caseInfo['headcount'];
				$this->view->total = $caseInfo['catering_total'];
				$this->view->notes = $caseInfo['catering_notes'];
				$this->view->status = "OK";
			}
			else
			{
				$this->view->status = "NOT_OK";
				$this->view->message = "Case not found for $case_number.";
			}
		}
		else
		{
			$this->view->status = "NOT_OK";
			$this->view->message = "Case number is missing.";
		}
	}

	public function floralorderformAction()
	{
		$this->_helper->layout()->disableLayout();

		$request = $this->getRequest();
		$p = $request->getParams();
		$case_number = $p['case_number'];

		if(isset($case_number))
		{
			$cases = new FDMSCases();
			$results = $cases->getCaseInfoForFDMSCaseNum( $case_number );
			if($results['status'] == "SUCCEEDED")
			{
				$caseInfo = $results['rows'][0];
				$branch_number = $caseInfo['branch_num'];

				// get and parse the caterer and menu,
				// add headcount and total
				$floristStr = stripslashes($caseInfo['florist']);
				$floristStr = str_replace(":", "", $floristStr);

				// now let's look up the florists for the branch the case is assigned to
				// and find the one named herein
				$florists = new Florists();
				$rows = $florists->getFloristsAndCollectionsForBranch( $branch_number );
				$floristsAndMenusStr=$rows[0];
				$floristsAndMenusXML = simplexml_load_string( $floristsAndMenusStr );
				$foundFlorist = null;
				if(null != $floristsAndMenusXML)
				{
					foreach( $floristsAndMenusXML->florist as $florist )
					{
						if($floristStr == $florist->name)
						{
							$foundFlorist = $florist;
						}
					}
				}
				$this->view->florist = $foundFlorist;

				$collectionsStr = $caseInfo['arrangement'];
				$collectionsXML = simplexml_load_string( $collectionsStr );
				$this->view->collections = $collectionsXML;
				$this->view->notes = $caseInfo['floral_notes'];
				$this->view->total = $caseInfo['floral_total'];
				$this->view->status = "OK";
			}
			else
			{
				$this->view->status = "NOT_OK";
				$this->view->message = "Case not found for $case_number.";
				$this->view->collections = array();
			}
		}
		else
		{
			$this->view->status = "NOT_OK";
			$this->view->message = "Case number is missing.";
		}
	}

	public function teststatsAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$page = "TEST";
		$branch = 1;
		$case = "BOOGA";
		$arranger = 1;
		$locale = 1;
		$region = 1;
		$elapsed = 1234567/1000; // milliseconds, so divide by 1000

		$moduleTimes = new VASModuleTimes();
		$res = $moduleTimes->recordTimeInModule(
		$page,
		$case,
		$locale,
		$branch,
		$region,
		$arranger,
		$elapsed );
		Zend_Debug::dump($res);
	}

	public function branchesforregionAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();

		$cases = new FDMSCases();
		$moduleTimes = new VASModuleTimes();

		$astats = $moduleTimes->statsForBranch(5);
		$arevs = $cases->getCaseStatsForBranch(5);

		Zend_Debug::dump($astats);
		Zend_Debug::dump($arevs);
		exit(0);

		// test method to verify region -> branch list
		$homes = new FuneralHomes();
		$stats = new VASCaseStatistics();

		$results = $homes->getFuneralHomesInRegion(1);
		$branches = $results['rows'];

		$results = $cases->getFinishedCasesForBranch(1);

		$results = $cases->getFinishedCasesForBranch(2);

		$results = $cases->getFinishedCasesForRegion(1);

		$results = $stats->regionStats( 1 );
		var_dump($results[0]);
		var_dump($results[1]);
	}

	public function addvastimingrecordAction()
	{
		$this->getHelper('viewRenderer')->setNoRender();
		$this->_helper->layout()->disableLayout();
		$request = $this->getRequest();

		$results = array();
		if($request->isPost())
		{
			$p = $request->getParams();

			$page = $p['page'];
			$branch = $p['branch'];
			$case = $p['case'];
			$arranger = $p['arranger'];
			$locale = $p['locale'];
			$region = $p['region'];
			$elapsed = $p['elapsed']/1000; // milliseconds, so divide by 1000

			$moduleTimes = new VASModuleTimes();
			$res = $moduleTimes->recordTimeInModule( $page, $case, $locale, $branch, $region, $arranger, $elapsed );

			$results['status'] = $res['status'];
			//			$results['page'] = $page;
			//			$results['branch'] = $branch;
			//			$results['case'] = $case;
			//			$results['arranger'] = $arranger;
			//			$results['locale'] = $locale;
			//			$results['region'] = $region;
			//			$results['elapsed'] = $elapsed;
		}
		echo json_encode($results);
	}
}
?>
